How it works...

In this recipe, we utilized the capability of C's union function to map the representation of different data types to the same memory space.

We define a union with two data fields  an array of 8-bit integers and a single 32-bit integer. These data fields share the same memory, so changes that are made in one field are automatically reflected in another field:

  union {
uint32_t i;
uint8_t c[4];
} data

Next, we assign the 32-bit integer field a specially crafted value, where each byte is known in advance and different from any of the others. We used bytes with values of one, two, three, and four to compose the target value.

When the value is assigned to the 32-bit field, i, it automatically rewrites all the fields into the c byte array field. Now, we can read the first element of the array, and, depending on what we read, we can infer the endianness of the hardware platform.

If the value is one, this means that the first byte contains the most significant byte, and hence the architecture is big-endian. Otherwise, it is little-endian. When we run the binary, it produces the following output:

As we can see, the program detected our system as little-endian. This technique can be used to detect the endianness in our runtime and adjust the application logic accordingly.