Sign in to follow this  
LonelyStar

Byte order and the shift operator ()

Recommended Posts

LonelyStar    192
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
darookie    1441
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
Rattrap    3385
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this