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

I want to…

Arrange bytes in memory

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.

At increasing addresses, the Big-endian representation is 81 53 B2 A0. Each byte stays intact. Interpreting these bytes as Big-endian gives the original 32-bit value 0x8153B2A0.

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