01: bool isLittleEndian()
02: {
03:   // 16 bit value, represented as 0x0100 on Intel, and 0x0001 else
04:   short pattern = 0x0001;
05:   // access first byte, will be 1 on Intel, and 0 else
06:   return *(char*) &pattern == 0x01;
07: }

Explanation 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.

Restrictions • none

These ads
help me to pay
my server bills

Download The full source code including a test program is available for download.
A precompiled Windows command-line executable (61 kB) is available as well.

References unknown

More Twiddled Bits
  1. Absolute value of a float
  2. Absolute value of an integer
  3. Approximative inverse of a float
  4. Bit manipulation basics
  5. Bit mask of lowest bit not set
  6. Count bits set in parallel a.k.a. Population Count
  7. Detects zero bytes inside a 32 bit integer
  8. Endianess
  9. Extend bit width
  10. Float inverse square root approximation
  11. Float square root approximation
  12. Is power of two
  13. Minimum / maximum of integers
  14. Parity
  15. Position of lowest bit set
  16. Round up to the next power of two
  17. Sign comparison
  18. Sign of a 32 bit integer
  19. Swap two values
Extra: Javascript bit manipulator

... or go to the index