Checking system endianness at runtime
What you'll learn: How to use a single integer and a character pointer to detect if your processor stores bytes in Little-Endian or Big-Endian order.
The Mailbox Analogy
Imagine you have a long, thin package (a 4-byte int) that you want to store in a row of four small mailboxes (memory addresses). If the number is 0x00000001, where does that 1 go?
A Little-Endian system is like a "last-letter-first" filing system; it puts the "little end" (the 01) in the very first mailbox. A Big-Endian system acts like we read English; it puts the "big end" (the 00) in the first mailbox and saves the 01 for the very last one.
The Memory Peek Technique
Because C allows us to look at memory addresses directly, we can solve this mystery with a simple experiment. We create an integer set to the value 1. Then, we take a char pointer and point it at that integer. Since a char is exactly one byte, it will only "see" the very first mailbox in the row.
If the char sees a 1, the system is Little-Endian. If it sees a 0, the system is Big-Endian.
The Implementation
Here is how you can write a quick check in your code:
#include <stdio.h>
int main() {
unsigned int test_val = 1;
// Point a character pointer to the address of our integer
// We cast it to (char*) so we can look at memory byte-by-byte
char *byte_ptr = (char*)&test_val;
// Look at the very first byte in memory
if (*byte_ptr == 1) {
printf("System is Little-Endian\n");
} else {
printf("System is Big-Endian\n");
}
return 0;
}
Why this works
In memory, the number 1 is represented as 00 00 00 01 (in hex).
- On Little-Endian (most modern desktops and laptops), the bytes are swapped in storage:
[01] [00] [00] [00]. Our pointer looks at the first slot and finds01. - On Big-Endian, the bytes stay in "natural" order:
[00] [00] [00] [01]. Our pointer looks at the first slot and finds00.
This runtime check is essential when writing code that sends data over a network or saves binary files that might be opened on a different type of computer.
Key takeaway
By casting an integer's address to a char*, you can inspect the first byte of storage to determine if the system uses Little-Endian or Big-Endian ordering.