How to split a 16bit value into MSB and LSB?


I have values between 0 and 65536 and I would like to get the high byte (MSB) and the low byte (LSB) of it.

For example my value is 2400 decimal:
2400/256=9,375 --> 09 is the High byte. 9,375-9=0,375 --> 0,375*256=96 --> 96decimal to hex = 60 --> low byte = 60

I have tried the following:
LoByte = HighThreshold & 0x00ff;
HiByte = (HighThreshold & 0xff00)>>8;

The result is 96 for LoByte and 0 for HiByte, so this is wrong.

LoByte = lowByte(HighThreshold); //found in wire.h
HiByte = highByte(HighThreshold);
The result is 96 for LoByte and 0 for HiByte, so this is wrong too.

The solution is within my reach but I can't find the last piece in the puzzle. So any help is greatly appreciated!

Post the rest of your code, using code tags ("</>" button). That is where the problem is.

Your formulas there are perfectly correct. If you just set HighThreshold to 2400 and run it through those you will end up with LoByte = 96, HiByte = 9. Naturally, HighThreshold must be a datatype that is 16 bits large.

uint16_t HighThreshold = 2400;
byte LoByte = (HighThreshold & 0x00FF);
byte HiByte = ((HighThreshold & 0xFF00) >>8);
Serial.print( "High Threshold: " );   Serial.println( HighThreshold, HEX );  // <-- prints 960
Serial.print( "Hi Byte: " );   Serial.println( HiByte, HEX );   // <-- prints 9
Serial.print( "Lo Byte: " );   Serial.println( LoByte, HEX );   // <-- prints 60

Is this not what you see? If not what are you getting? I will suggest that you have either mistakenly assumed that your HighThreshold value was set to a value that it was not set to, or that you typed it with a size less than 16 bits. And you have blamed the mistake on your code. But the code is fine.

Thank you very much for your help! After reading your answer and looking at your code I saw the mistake. I have used uint8_t for HighThreshold...

Now it is working as it should :slight_smile: Sometimes I don't see the wood for the trees :smiley:
Thank you very much again!

... Sometimes I don't see the wood for the trees :smiley: ...

Evidently there exists no human that can.