 understanding bytes and the serial monitor

I've tried to read lots but nothing is fully in 'newbie speak'....

I have a simple piece of code and am trying to split an integer into two bytes. The end goal being to send the result vis srial comms and the reassemble the integer.

int num = 52;

void setup() {
Serial.begin (115200);
}

void loop() {
byte H = highByte (num/10);
byte L = lowByte (num%10);
Serial.println(h,BIN);
Serial.println (l,BIN);
}

As far as I understand int is a max of 16 bits and byte is 8 bits.

In the program, H should return 5 in binary and L should return 2 in binary but all i get is

0
10

Each byte can represent a value of up to 255 so why isnt 52 reporting correctly? Is it because 52 is covered by the lowbyte only (52 is 00110100) so there is no highbyte?

what is a byte?
what is the hexadecimal value of "num" (52)?
what is the binary value of "num"?

do you really want to print the value as binary (BIN)? or HEX, or DEC?

Leaving aside for the moment that the code that you posted does not compile, try this

void setup()
{
Serial.begin (115200);
while (!Serial);
for (int num = 250; num <= 260; num++)
{
splitIntoBytes(num);
}
}

void loop()
{
}

void splitIntoBytes(int x)
{
Serial.print(x);
Serial.print("\tH : ");
byte H = (x >> 8);  //get the upper 8 bits of the int
byte L = x & 0x00FF;  //get the lower 8 bits of the int
Serial.print(H, BIN);
Serial.print("\tL : ");
Serial.println (L, BIN);
}

Thanks. I think I understand what you are doing.

Very basic question.

In the function you created (splitIntobytes) how do the two lines actually 'get' the upper and lower 8?

byte H = (x >> 8);  //get the upper 8 bits of the int
byte L = x & 0x00FF;  //get the lower 8 bits of the int

For numbers below 255 then only the lower bytes are printed?

Once I get the last piece this is very useful. Thankyou.

H is the result of shifting the int 8 bits to the right. The lower 8 bits of the int are lost and the upper 8 bits end up in the byte

L is the result of logically anding the int with hex FF which just leaves the lower 8 bits of the int
If it helps then try this

void splitIntoBytes(int x)
{
Serial.print(x);
Serial.print("\tH : ");
byte H = (x / 256);  //get the upper 8 bits of the int
byte L = x % 256;  //get the lower 8 bits of the int
Serial.print(H, BIN);
Serial.print("\t");
Serial.println (L, BIN);
}

Your original mistake was in dividing by 10 rather than 256 but bit shifting and masking are much faster that doing arithmetic

"x >> 8" means shift x right by 8 bits. This causes the high order byte to be shiftet into the low order byte. "x & 0x00FF" or "x & 0xFF" means that you only want the bits in the low order byte.

EDIT: Right is left when wrong is purged "x >> 8" means shift x left by 8 bits

?

Danois90:
“x >> 8” means shift x left by 8 bits.

sp. “right”