Hello!
Consider this code:
If the processor operates with little endianess, the code will print 256. But what if it has big endianess, will it print 0?Code:unsigned int i = 1;
i <<= 8;
printf("%d\n", i);
Printable View
Hello!
Consider this code:
If the processor operates with little endianess, the code will print 256. But what if it has big endianess, will it print 0?Code:unsigned int i = 1;
i <<= 8;
printf("%d\n", i);
1 << 8 will be 256 in all systems.
The byte-order (endianness) is only relevant when the processor stores the data in memory. The internal structure of a CPU register has all bits in a logical order from 0..n, in a logical right to left order. This register may be stored as 4 bytes in either big or little endian order - but shifting it 8 bits will still shuffle the entire number 8 bits to the left (or right), because this happens internally in the CPU, not on the memory outside the CPU.
--
Mats
Ok, but this example:
will print 00010203 if the processor uses little endianess, but 03020100 if the processor uses big endianess? Or have I got it wrong?Code:char a[4];
a[0] = 0;
a[1] = 1;
a[2] = 2;
a[3] = 3;
printf("%.8X", *(int*)a);
Yes (unless I mixed up which endianess is what).
In fact, it's the inverse, if the processor is little endian, it will print 03020100, and if it's big endian, it will print 00010203.Quote:
Originally Posted by TriKri
Of course, we are also assuming that the processor is adressing bytes, and not something more "exotic", e.g. 16-bits words.
in other words, as long as you don't reinterpret the bit pattern as some other type then whatever manipulations/transformations you perform will be portable. otherwise, you are treading the waters of undefined behavior. ;)