Skip to content

Known Bytes Beat Matching Mistakes

The Course
•
40 min study

The most natural test for a codec is a round trip: encode a record, decode the bytes, and check you get the same record back. It is a good test, and the project runs it over a whole grid of readings. But it has a blind spot that matters a great deal for wire formats. A round trip checks that the encoder and decoder agree with each other. It does not check that either of them agrees with the protocol. If both were written by the same person with the same misunderstanding, such as little-endian fields or the checksum at the wrong offset, every round trip passes, and the first real device that talks to your code disagrees on every frame.

The fix is a fixture: a set of bytes whose correctness was established independently of the code under test. For this protocol the main fixture is the ten bytes for sensor 1, value 25, derived by hand on Day 3 from the specification: 54 01 01 00 04 00 01 00 19 74. A test that compares the encoder's output with those bytes, and decodes those bytes and checks the fields, pins both directions to the specification rather than to each other.

Predict and run

Read the program before pressing Run. Predict the output, then explain why comparing decoded fields alone would not catch an encoder and decoder that share the same byte-order mistake.

Predict before running C
#include <stdio.h>
#include <string.h>

int main(void) {
    unsigned char expected[2] = {0x01,0x02};
    unsigned char actual[2] = {1,2};
    puts(memcmp(expected,actual,2) == 0 ? "Match" : "Mismatch");
    return 0;
}
Check your prediction
Text
Match

memcmp compares bytes and returns 0 when all of them are equal. 0x01 and 1 are the same value written two ways. memcmp is the right tool for byte arrays, and the wrong tool for structs: padding bytes inside a struct have unspecified values, so two structs with equal fields can still compare unequal byte by byte. Compare struct fields one at a time instead.

A pair of matching mistakes

Here is a codec whose author got the byte order backwards in both directions. Watch which test notices:

Round trip passes, fixture fails C
#include <stdio.h>
#include <string.h>

static void encode_le(unsigned char out[2], unsigned value) {      /* wrong order */
    out[0] = (unsigned char)(value & 0xFFu);
    out[1] = (unsigned char)(value >> 8);
}
static unsigned decode_le(const unsigned char in[2]) {             /* same mistake */
    return ((unsigned)in[1] << 8) | in[0];
}

int main(void) {
    unsigned char bytes[2];
    int round_trips = 0;
    for (unsigned value = 0; value <= 10000; value += 2500) {
        encode_le(bytes, value);
        round_trips += decode_le(bytes) == value;
    }
    printf("round trips passed: %d of 5\n", round_trips);
    const unsigned char fixture[2] = {0x00, 0x19};   /* 25, big-endian, from the spec */
    encode_le(bytes, 25);
    printf("fixture: %s\n", memcmp(bytes, fixture, 2) == 0 ? "match" : "mismatch");
    printf("decoding the fixture gives %u\n", decode_le(fixture));
    return 0;
}
Text
round trips passed: 5 of 5
fixture: mismatch
decoding the fixture gives 6400

Five out of five round trips pass, which would look like strong evidence. The single fixture test exposes the bug in both directions: the encoder produces the wrong bytes, and the decoder reads real-world bytes as 6400 instead of 25. One fixture test is worth more than any number of round trips for this class of bug, and the round trips still earn their place by covering many values cheaply once the fixture has anchored the format.

Where trustworthy fixtures come from

The expected bytes must not come from the code being tested. Running the encoder once and pasting its output into the test, a common shortcut sometimes called a snapshot, freezes whatever the encoder does today, bugs included. Good sources, roughly from strongest to weakest:

  • The specification, worked by hand. Derive each octet, and show the arithmetic in a comment so a reviewer can check it.
  • Captured output from a real device or a second, independent implementation.
  • Published test vectors, when a standard provides them.

Choose fixtures at the boundaries as well as in the middle. For this protocol, sensor 4095 with value 10000 exercises the largest values: 54 01 01 00 04 0F FF 27 10 9F, where 0x0FFF is 4095, 0x2710 is 10000, and the checksum is 84 + 1 + 1 + 4 + 15 + 255 + 39 + 16 = 415, and 415 minus 256 is 159, which is 0x9F. Value 0 is a valid reading, so it needs a fixture too, or a decoder that treats 0 as "missing" would slip through.

When the format changes, update the specification and the fixtures in the same change. A fixture edited only to make a failing test pass has stopped being independent evidence.

Practice

Exercise

Your turn

Write a big-endian encode_frame(sensor, value, out) for the full ten-byte frame. Derive the fixture for sensor 1 with value 0 by hand, and add it to the two fixtures given in the starter. Compare the encoder's output with each fixture, then check one round trip. Print:

Text
1/25: match
4095/10000: match
1/0: match
round trip 4095/10000: ok
Your workspace C
#include <stdio.h>
#include <string.h>

static const unsigned char fixture_1_25[10] = {0x54, 1, 1, 0, 4, 0x00, 0x01, 0x00, 0x19, 0x74};
static const unsigned char fixture_max[10] = {0x54, 1, 1, 0, 4, 0x0F, 0xFF, 0x27, 0x10, 0x9F};
/* Derive this one by hand from the specification. */
static const unsigned char fixture_1_0[10] = {0x54, 1, 1, 0, 4, 0, 0, 0, 0, 0};

int main(void) {
    /* Write encode_frame above, then compare it with each fixture here. */
    (void)fixture_1_25; (void)fixture_max; (void)fixture_1_0;
    return 0;
}
Hint 1: the idea

For sensor 1, value 0, the payload is 00 01 00 00. The checksum is the header sum plus the payload sum, all modulo 256, and the header alone sums to 0x54 + 1 + 1 + 0 + 4.

Hint 2: a first step

The header sums to 90. Add the four payload octets, reduce modulo 256, and write the result in hex at offset 9. Then write a helper check(label, sensor, value, fixture) that encodes and prints match or mismatch with memcmp.

Show one solution
Run the solution C
#include <stdio.h>
#include <string.h>

static const unsigned char fixture_1_25[10] = {0x54, 1, 1, 0, 4, 0x00, 0x01, 0x00, 0x19, 0x74};
static const unsigned char fixture_max[10] = {0x54, 1, 1, 0, 4, 0x0F, 0xFF, 0x27, 0x10, 0x9F};
/* 0x54+1+1+0+4 = 90; payload 00 01 00 00 adds 1; checksum 91 = 0x5B. */
static const unsigned char fixture_1_0[10] = {0x54, 1, 1, 0, 4, 0x00, 0x01, 0x00, 0x00, 0x5B};

void encode_frame(unsigned sensor, unsigned value, unsigned char out[10]) {
    unsigned char frame[10] = {0x54, 1, 1, 0, 4, 0, 0, 0, 0, 0};
    frame[5] = (unsigned char)(sensor >> 8); frame[6] = (unsigned char)(sensor & 0xFFu);
    frame[7] = (unsigned char)(value >> 8);  frame[8] = (unsigned char)(value & 0xFFu);
    unsigned char sum = 0;
    for (size_t i = 0; i < 9; ++i) { sum = (unsigned char)(sum + frame[i]); }
    frame[9] = sum;
    memcpy(out, frame, 10);
}

static void check(const char *label, unsigned sensor, unsigned value, const unsigned char *fixture) {
    unsigned char out[10];
    encode_frame(sensor, value, out);
    printf("%s: %s\n", label, memcmp(out, fixture, 10) == 0 ? "match" : "mismatch");
}

int main(void) {
    check("1/25", 1, 25, fixture_1_25);
    check("4095/10000", 4095, 10000, fixture_max);
    check("1/0", 1, 0, fixture_1_0);
    unsigned char out[10];
    encode_frame(4095, 10000, out);
    unsigned sensor = ((unsigned)out[5] << 8) | out[6], value = ((unsigned)out[7] << 8) | out[8];
    printf("round trip 4095/10000: %s\n", sensor == 4095 && value == 10000 ? "ok" : "failed");
    return 0;
}
Text
1/25: match
4095/10000: match
1/0: match
round trip 4095/10000: ok

The comment above fixture_1_0 is part of the test. It lets a reviewer check the expected bytes without trusting either you or the encoder. The three fixtures anchor the low end, the high end and the zero value, and the round trip then confirms the decoder agrees. Next, you generalize from a few hand-picked cases to properties checked across many inputs and every chunking.

Was this article helpful?

Your response is saved on this device.