Simvik

Read a big-endian word

Assemble a 32-bit value from four bytes of a packet. An easy embedded C problem (Protocols, framing and checksums), run and graded in the browser.

easy · Protocols, framing and checksums · endianness · parsing

Network protocols send the most significant byte first. Return the 32-bit value stored big-endian in the four bytes at p.

p may point anywhere in a packet, so it is not necessarily aligned to 4 bytes.

Starter code

uint32_t read_be32(const uint8_t *p) {
  // Reads little-endian on this CPU, and assumes p is 4-byte aligned.
  return *(const uint32_t *)p;
}

Example tests

Four distinct bytes

const uint8_t b[] = { 0x12, 0x34, 0x56, 0x78 };
printf("0x%08X\n", read_be32(b));

Expected output:

0x12345678

A small number

const uint8_t b[] = { 0x00, 0x00, 0x01, 0x00 };
printf("%u\n", read_be32(b));

Expected output:

256

Learn it first

More Protocols, framing and checksums problems