Endianness & Byte Order in C
Multi-byte values store bytes in an order: little-endian (x86, ARM by default) puts the least significant byte first; big-endian (network order, some embedded) puts the most significant first. Same memory, different integer readings — which is why binary files and protocols must pick one order explicitly.
Detect at run time with a union/int-pointer probe, convert with htonl/htons (host-to-network) and ntohl/ntohs on sockets, and serialize field-by-field with shifts (buf[i] = (v >> 8) & 0xFF) for order-independent formats. Text and single bytes never care; everything wider must decide.
Two orders, one memory
0x01020304 reads 04 03 02 01 on little-endian, 01 02 03 04 on big-endian — byte sequences differ, values shouldn't.
Network order is big-endian
htonl/htons convert host values for the wire; ntohl/ntohs convert back — no-ops where host already matches.
Probe when curious
Store 1 in an int and read the first byte: 1 means little-endian, 0 means big — a three-line runtime test.
Serialize explicitly
Shift-and-mask field writers produce identical bytes on every platform — order decided by code, not CPU.
#include <stdio.h>#include <stdint.h> int main(void) { uint32_t v = 1; printf("%d\n", *(unsigned char *)&v); uint32_t net = 0x01020304u; unsigned char *b = (unsigned char *)&net; printf("%02x%02x\n", b[0], b[1]); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.