Learn C
#include "systems/endianness.h"

Endianness & Byte Order in C

#concept

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.

#how it works
1

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.

2

Network order is big-endian

htonl/htons convert host values for the wire; ntohl/ntohs convert back — no-ops where host already matches.

3

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.

4

Serialize explicitly

Shift-and-mask field writers produce identical bytes on every platform — order decided by code, not CPU.

#example
#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;
}
Output
1
04
1Reading value 1's first byte yields 1 on little-endian machines (nearly all desktops) — the probe result.
20x01020304's first two bytes read 04 03 on little-endian; the print shows the leading pair.
3Both probes expose storage order directly — the concept made observable.
#use cases
Network code converting every multi-byte field with hton/ntoh
File formats specifying byte order explicitly in their spec
Shift-based serializers immune to host order
Probing order at run time in portable libraries

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.