How to use high and low bytes?

Sterling picture Sterling · May 22, 2011 · Viewed 58k times · Source

I am trying to represent 32768 using 2 bytes. For the high byte, do I use the same values as the low byte and it will interpret them differently or do I put the actual values? So would I put something like 32678 0 or 256 0? Or neither of those? Any help is appreciated.

Answer

John McFarlane picture John McFarlane · May 22, 2011

In hexadecimal, your number is 0x8000 which is 0x80 and 0x00. To get the low byte from the input, use low=input & 0xff and to get the high byte, use high=(input>>8) & 0xff.

Get the input back from the low and high byes like so: input=low | (high<<8).

Make sure the integer types you use are big enough to store these numbers. On 16-bit systems, unsigned int/short or signed/unsigned long should be be large enough.