Simvik

Fix: frame lengths come out 256 times too big

A big-endian length field is decoded as little-endian. An easy embedded C problem (Protocols, framing and checksums), run and graded in the browser.

easy · Protocols, framing and checksums · find-the-bug · endianness · parsing

Bug report. Frames from the modem start with a two-byte length in big-endian order (network byte order: the most significant byte first). For a frame whose header bytes are 00 03, frame_length returns 768 instead of 3, and the parser waits forever for bytes that never come. Fix it by changing one line.

Starter code

uint16_t frame_length(const uint8_t *hdr) {
  return (uint16_t)(hdr[0] | (hdr[1] << 8));
}

Example tests

Short and long frames

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

Expected output:

3 256

Learn it first

More Protocols, framing and checksums problems