# Byte order and the shift operator ()

## 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 on other sites
Quote:
 Original post by LonelyStarNow 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 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.

I feel relieved!
Thanks!
Nathan

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628348
• Total Posts
2982208

• 10
• 9
• 24
• 11
• 9