Simvik

Convert a header to host order

Fix up the multi-byte fields of a received big-endian header. A medium embedded C problem (Structs, unions and memory layout), run and graded in the browser.

medium · Structs, unions and memory layout · endianness · networking

A header has been copied byte for byte from a network buffer into header_t. The protocol is big-endian, the CPU is little-endian, so every multi-byte field currently holds the wrong value.

Convert all three fields to host byte order, in place.

Starter code

void header_to_host(header_t *h) {
  // Each field was stored most significant byte first.
}

Example tests

Typical header

const uint8_t raw[8] = { 0x00, 0x01, 0x00, 0x10, 0x12, 0x34, 0x56, 0x78 };
header_t h;
memcpy(&h, raw, sizeof h);
header_to_host(&h);
printf("%u %u 0x%08X\n", h.type, h.length, h.sequence);

Expected output:

1 16 0x12345678

Large field values

const uint8_t raw[8] = { 0xAB, 0xCD, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01 };
header_t h;
memcpy(&h, raw, sizeof h);
header_to_host(&h);
printf("%u %u 0x%08X\n", h.type, h.length, h.sequence);

Expected output:

43981 65535 0x00000001

Learn it first

More Structs, unions and memory layout problems