Endianness and binary portability
What you'll learn: How the internal byte order of numbers can break your data when sharing binary files between different computer systems.
The "Date Format" Problem
Imagine you write the date "01/02" in your notebook. If you are in the US, you mean January 2nd. If you are in Europe, you mean February 1st. The data is the same, but the interpretation depends on local rules.
Computers face a similar issue with multi-byte numbers, like a 4-byte int. When you save an integer to a binary file, the CPU has to decide which byte to write first: the "big" end (most significant) or the "little" end (least significant). This is called Endianness.
Big-Endian vs. Little-Endian
- Big-Endian: Stores the most significant byte at the lowest memory address. It reads left-to-right, like human writing.
- Little-Endian: Stores the least significant byte first. Most modern consumer PCs (Intel and AMD) use this.
If you save the hexadecimal value 0x12345678 to a binary file on a Little-Endian PC, it actually sits on the disk as 78 56 34 12. If you then send that file to a Big-Endian system and read it, the computer will see 0x78563412—a completely different number!
Achieving Portability
Binary files are not "plug and play" across different architectures unless you standardize them. To ensure your binary files work everywhere, programmers usually convert data to a "Network Byte Order" (which is Big-Endian) before writing to disk.
#include <stdio.h>
#include <stdint.h>
// Concept: Writing an integer in a specific order
void write_fixed_int32(FILE *f, int32_t value) {
unsigned char bytes[4];
// Manually extracting bytes ensures the same order
// regardless of the computer's internal CPU architecture
bytes[0] = (value >> 24) & 0xFF; // Most significant
bytes[1] = (value >> 16) & 0xFF;
bytes[2] = (value >> 8) & 0xFF;
bytes[3] = value & 0xFF; // Least significant
fwrite(bytes, sizeof(unsigned char), 4, f);
}
By manually shifting bits as shown above, you guarantee that the file always looks the same on the disk, making your binary data portable across any hardware.
Key takeaway
Binary files are sensitive to CPU architecture; always standardize your byte order (serialization) to ensure files created on one computer can be read by another.