views:

64

answers:

4

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?

+3  A: 

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;
DarkDust
+1  A: 

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

Secure
A: 

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]);
Amigable Clark Kant
Thanks all for your responses. Will it be correct to summarize the responses as follows:
Bikash
@Bikash, you hit enter too early? :-)
Amigable Clark Kant
1. My protocol requires the byte order of the message to be big endian
Bikash
2. On the sender machine, I have uint32_t num, and I denote the 4 bytes of num as num0 ... num3, with num0 being the LSB and num3 the MSB. Under this scenario, the code posted sends the message in the desired format irrespective of the endianness of the sender machine.
Bikash
3. On the receiving machine, I read in num2 first, followed by num1 and then num0. So, in order to reconstruct the 24-bit version of num, I should use the following irrespective of the endianness of the receiving machine:
Bikash
num24 = (num2 << 16) + (num1 << 8) + num0.
Bikash
A: 

int main(int argc, char** argv) {

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

}

There is number a contain 32 bit value but number b contain only 24 bit's start from least significant digit. And that's not depend on endian because bitwise operator not work with memory representation.

So you use

num = num & ( ~0xff000000 );

for get least 24 bit value.

Anand Kumar
Is there something wrong with 0x00ffffff?
Secure
It's also work so that time no need to Not operator (~ ) . That more optimal solution.
Anand Kumar