The memory layout of numbers depends on the CPU and has to be considered when designing a bit twiddler.
Intel's x86 chips (and of cause compatible chips from AMD etc.) rely on "little endian":
Numeric values consisting of multiple bytes have increasing numeric significance with increasing memory addresses.
The opposite, called big endian, is true for Motorola chips, PowerPC and various other designs.
A few CPUs can even switch at runtime like ARM or newer PowerPC or x64.
The programming language C itself usually takes care of the endianness but whenever direct memory access is
requires by the software, it might be important to know the endianness of the system.
Here is the idea:
A known number consisting of more than one byte is stored. The single bytes must not repeat.
For simplicity, the number 0x0001 and data type short is chosen (line 4).
Little endian stores it as 0x01, 0x00 whereas big endian stores 0x00, 0x01.
Then the short's memory address is accessed via a char pointer, which refers to the first byte (line 6).
If it points at 0x01, then we have a little endian architecture.
This information can be gathered at compile time by smart compilers and thus often comes "for free" because the
code is reduced to a simple assignment of true or false.
help me to pay
my server bills
The full source code including a test program is available for download.
A precompiled Windows command-line executable (61 kB) is available as well.
|More Twiddled Bits||
... or go to the index