• Advertisement
Sign in to follow this  

Byte order and the shift operator ()

This topic is 4520 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi together, I am a little confused. I debugged a programm using gdb with the following commands: (gdb) p val $12 = 524288 (Inserted comment: 524288=0x00 08 00 00) (gdb) p ((unsigned char*)&val)[0] $14 = 0 '\0' (gdb) p ((unsigned char*)&val)[1] $15 = 0 '\0' (gdb) p ((unsigned char*)&val)[2] $16 = 8 '\b' (gdb) p ((unsigned char*)&val)[3] $17 = 0 '\0' (gdb) p ((unsigned char*)&val)[4] My CPU is a x86 CPU. OK, this output suggest, that the x86 uses "little endian" for storing numbers. (Or I am not seeing something). Now I compile the following programm:
int main()
{
  printf("%i\n",0xFF<<8);
}

Output: 65280 (=0xFF00, =0xFF*256) Now I am confused! Also the x86 stores integers in little endian, shifting a byte to the left multiplies the number by 256. Does this mean that on the x86 stores numbers in little endian byte order BUT the "<<" operator is implemented so smart, that it is as if the numbers would be stored in big endian order? Thanks! Nathan

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by LonelyStar
Now I am confused! Also the x86 stores integers in little endian, shifting a byte to the left multiplies the number by 256. Does this mean that on the x86 stores numbers in little endian byte order BUT the "<<" operator is implemented so smart, that it is as if the numbers would be stored in big endian order?
Thanks!
Nathan

The binary shift operators (and all binary operators) are agnostic to byte ordering. You can rely on their behaviour regardless of the internal byte-order of the host CPU. Otherwise you wouldn't be able to write portable code even at the language level [wink].

Share this post


Link to post
Share on other sites
The numbers are stored in little-endian format in memory. Endian issues usually stem from reading from files or other outside sources, where you need to convert to the appropriate endian-ness.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement