SNIPPET 5

Endianness Detection

Write logic to dynamically detect the system's memory endianness.

Silicon Logic

CPUs store multi-byte numbers in RAM in two different ways:

Little Endian: The least significant byte (LSB) is stored at the lowest memory address.
Big Endian: The most significant byte (MSB) is stored at the lowest memory address.

If we define an integer 0x0001, a Little Endian system stores `0x01` at index 0 and `0x00` at index 1. A Big Endian system stores `0x00` at index 0 and `0x01` at index 1.

By casting a 16-bit integer pointer down to an 8-bit pointer, we force the CPU to read only the lowest address index. If it returns 1, we are Little Endian.

endianness_detect.c
#include <stdint.h>
#include <stdbool.h>
bool is_little_endian() {
uint16_t val = 0x0001; // 2 bytes
uint8_t *ptr = (uint8_t *)&val; // Read only the lowest byte
return (*ptr == 0x01);
}
int main() {
bool is_le = is_little_endian();
return 0;
}