Last Updated: February 25, 2016
· srijs

Endianness-indicating Compile Time Expression in C

Ever needed to write C-code that is aware of the local machines endianness?

#define endianness (!(union{uint16_t x;uint8_t y;}){1}.y)

The code constructs a union of 8-bit and 16-bit integers, and assigns the value 0x0001 to the 16-bit field. Because fields in a union are left-aligned in memory, running the code on a big-endian machine yields the value 1 for the 8-bit field, or 0 otherwise.

Compilers are usually smart enough to evaluate this expression at compile-time, resulting in zero-cost endianness checking vs. the usual approach using stdlib's htons.

Say Thanks