SYSTEMS / Learn
Saved on this device>
← Back to goals

I want to…

Convert little- and big-endian

Trace this example, understand why the operation works, then try it from memory.

1 · Choose a goal → 2 · Learn the method → 3 · Practise → 4 · Spaced review

Learn the method

Same integer. Different byte order.Move whole bytes; never reverse the bits or the two hex digits inside a byte.

The original Little-endian bytes are A0 B2 53 81. Reversing the byte sequence gives 81 53 B2 A0 in Big-endian. Both layouts represent 0x8153B2A0; only the mapping from byte significance to memory addresses changes.

IN CODEC17
#include <stdint.h>
uint32_t x = UINT32_C(0x8153B2A0);

uint8_t bytes[4];
for (unsigned i = 0; i < 4; ++i)
    bytes[i] = (uint8_t)(x >> (8u * (3u - i)));

Serialize the original integer into the target byte order explicitly, independently of the host machine’s endianness. In C, run the statements inside a function.

CS:APP · §2.1.4

coffee-bytes / Systems LearningCS:APP + Hacker’s Delight