cendianness24-bit

How to write a 24 bit message after reading from a 4-byte integer on a big endian machine (C)?


I am constructing a message to send a 24-bit number over the network. For little endian machines, the code is (ptr is the pointer to the message buffer):

*ptr++ = (num >> 16) & 0xFF;
*ptr++ = (num >> 8)  & 0xFF;
*ptr++ = (num)       & 0xFF;

(So if num0, num1, num2 and num3 are the individual bytes making up num, the message would be encoded as num2|num1|num0.)

What should be the code for encoding num2|num1|num0 on a big endian machine?


Solution

  • Your code is portable regardless of endianess. The shift operators >> << work with the values, not with the representation.