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

StackOverflow https://stackoverflow.com/questions/3965873

  •  09-10-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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

OTHER TIPS

The question here is, in what byte order shall the message be sent/constructed ? Because whether you are on a little or big endian machine doesn't matter with respect to num, as you're already dividing num into individual bytes in an endian-agnostic way.

The code you've posted stores 24 bits of num in big endian (aka network byte order). So if that's what you want you're already done. If you want to store it in big little instead, just reverse the order:

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

In the receiving machine, regardless of endian-ness, if you receive them in same order as they are stored in ptr, assemble them like this:

num = (ptr[0] << 16) + (ptr[1] << 8) + (ptr[2]);
int main(int argc, char** argv) {

    int a, b;
    a = 0x0f000000;        // Contain 32 bit value
    printf("before = %d\n", a);
    b = a & (~0xff000000); // convert the last 8 bits to zero so we got only 24 bit value in b
    printf("After = %d\n", b);
    return (EXIT_SUCCESS);
}

There is a number containing a 32-bit value but number b contains only 24 bits, starting from least significant digit. And that doesn't depend on endianness because bitwise operators don't work with memory representation.

So you can use

num = num & (~0xff000000);

to get the last 24-bit value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top