Skip to content

Checkpoint: Encode a Header

The Course
•
50 min study

A protocol only exists if two independent programs agree on every byte. That agreement starts with a written specification, not with code. Here is version 1 of the telemetry frame, octet by octet:

  • Offset 0, magic: 0x54. A fixed marker that rejects obviously wrong input at the first byte.
  • Offset 1, version: 0x01.
  • Offset 2, type: 0x01, a reading. Other types are reserved and currently rejected.
  • Offsets 3 and 4, payload length: big-endian. A reading payload is exactly 4 octets; 16 is the defensive upper limit for any future type.
  • Offsets 5 and 6, sensor ID: big-endian, 1 to 4095.
  • Offsets 7 and 8, value: big-endian, 0 to 10000.
  • Offset 9, checksum: the sum of octets 0 to 8, modulo 256.

So a complete reading frame has ten octets, and the first five form the header. The checksum detects some accidental corruption; it does not authenticate the sender. In this checkpoint you write the encoder for a complete reading frame, all ten octets, straight from this specification. Nothing earlier today encoded more than one field; the design of this one is yours, built from Day 2's tools: unsigned octets, explicit big-endian writes and checks before any output changes.

Predict and run

Read the program before pressing Run. Write down its output and say which part of the format string produces the spaces and the newline.

Predict before running C
#include <stdio.h>

int main(void) {
    unsigned char header[5] = {0x54,1,1,0,4};
    for (size_t i = 0; i < sizeof header; ++i) { printf("%02X%s", (unsigned)header[i], i + 1 == sizeof header ? "\n" : " "); }
    return 0;
}
Check your prediction
Text
54 01 01 00 04

The conditional prints a space after every byte except the last, which gets a newline. The last two octets, 00 04, are the payload length 4 in big-endian order. Derive a length by hand to be sure of the rule: 258 is 256 + 2, so the high octet is 258 >> 8, which is 1, and the low octet is 258 & 0xFF, which is 2. The header for length 258 ends in 01 02. That header is representable on the wire, even though a version 1 decoder will reject it on Day 3 because a reading payload must be 4 octets. Representable and valid are different questions.

What you already have

  • Unsigned octets and explicit casts when narrowing (Bytes Are Not Text or Structs).
  • Big-endian writes that do not depend on the host (Read and Write Big-Endian Fields).
  • Range checks before narrowing, so a value that does not fit is rejected, not truncated.
  • An unchanged-output rule. On failure, neither the output bytes nor the written count change.

Plan before you type

Goals, not statements.

  1. Before any code, derive by hand the ten octets for sensor 7, value 250, including the checksum. Those are your expected bytes.
  2. Decide every reason the encoder refuses, and make sure all of them are decided before any byte of out changes.
  3. Decide how to write three 16-bit big-endian fields without writing the same two lines three times.
  4. Check every line of output, including the two lines that prove a refused call left the earlier output alone.

Practice

Exercise

Your turn

Write int encode_reading(unsigned char *out, size_t capacity, unsigned long sensor, unsigned long value, size_t *written). It encodes a complete version 1 reading frame (magic, version, type, payload length 4, sensor, value, checksum) as specified above, stores 10 in *written and returns 1. It returns 0, leaving out and *written unchanged, when capacity < 10, the sensor is outside 1..4095 or the value is above 10000. The starter must print:

Text
sensor 7 value 250: 54 01 01 00 04 00 07 00 FA 5B
sensor 4095 value 10000: 54 01 01 00 04 0F FF 27 10 9F
sensor 0 value 5: rejected, written still 10
sensor 7 value 10001: rejected, written still 10
capacity 9: rejected, last byte still 9F
Your workspace C
#include <stdio.h>
#include <string.h>

static void show(const unsigned char *bytes, size_t size) {
    for (size_t i = 0; i < size; ++i) { printf("%02X%s", (unsigned)bytes[i], i + 1 == size ? "" : " "); }
}

/* Write encode_reading here, with its contract comment. */

int main(void) {
    unsigned char out[10];
    size_t written = 0;
    const unsigned long cases[4][2] = {{7, 250}, {4095, 10000}, {0, 5}, {7, 10001}};
    for (size_t i = 0; i < 4; ++i) {
        printf("sensor %lu value %lu: ", cases[i][0], cases[i][1]);
        if (encode_reading(out, sizeof out, cases[i][0], cases[i][1], &written)) {
            show(out, written);
            printf("\n");
        } else {
            printf("rejected, written still %zu\n", written);
        }
    }
    if (!encode_reading(out, 9, 7, 250, &written)) {
        printf("capacity 9: rejected, last byte still %02X\n", (unsigned)out[9]);
    }
    return 0;
}
Hint 1: the idea

Build the whole frame in a local array, and copy it out only after every check has passed; then a failure has nothing to undo. The checksum is computed over octets 0 to 8 of that local frame, after the fields are in place.

Hint 2: a first step

Before any field, make the function fill a local unsigned char frame[10] with just the three fixed octets and the payload length, copy it out and return 1. Run it: the first line should start 54 01 01 00 04 and end in five zero octets. That fixes the frame's shape; the fields and the checksum then go into known positions.

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

static void show(const unsigned char *bytes, size_t size) {
    for (size_t i = 0; i < size; ++i) { printf("%02X%s", (unsigned)bytes[i], i + 1 == size ? "" : " "); }
}

static void put_be16(unsigned char *at, unsigned long value) {
    at[0] = (unsigned char)(value >> 8);
    at[1] = (unsigned char)(value & 0xFFUL);
}

/* Encodes a complete version 1 reading frame (10 octets).
   Returns 0, leaving out and *written unchanged, when capacity < 10,
   sensor is outside 1..4095 or value is above 10000. */
int encode_reading(unsigned char *out, size_t capacity, unsigned long sensor,
                   unsigned long value, size_t *written) {
    if (capacity < 10 || sensor < 1 || sensor > 4095 || value > 10000) { return 0; }
    unsigned char frame[10] = {0x54, 1, 1};
    put_be16(&frame[3], 4);
    put_be16(&frame[5], sensor);
    put_be16(&frame[7], value);
    unsigned sum = 0;
    for (size_t i = 0; i < 9; ++i) { sum += frame[i]; }
    frame[9] = (unsigned char)(sum & 0xFFu);
    memcpy(out, frame, sizeof frame);
    *written = sizeof frame;
    return 1;
}

int main(void) {
    unsigned char out[10];
    size_t written = 0;
    const unsigned long cases[4][2] = {{7, 250}, {4095, 10000}, {0, 5}, {7, 10001}};
    for (size_t i = 0; i < 4; ++i) {
        printf("sensor %lu value %lu: ", cases[i][0], cases[i][1]);
        if (encode_reading(out, sizeof out, cases[i][0], cases[i][1], &written)) {
            show(out, written);
            printf("\n");
        } else {
            printf("rejected, written still %zu\n", written);
        }
    }
    if (!encode_reading(out, 9, 7, 250, &written)) {
        printf("capacity 9: rejected, last byte still %02X\n", (unsigned)out[9]);
    }
    return 0;
}
Text
sensor 7 value 250: 54 01 01 00 04 00 07 00 FA 5B
sensor 4095 value 10000: 54 01 01 00 04 0F FF 27 10 9F
sensor 0 value 5: rejected, written still 10
sensor 7 value 10001: rejected, written still 10
capacity 9: rejected, last byte still 9F

The expected lines came from the specification, not from running the encoder, which is what makes them evidence. A small put_be16 helper writes each 16-bit field in one place, so the byte order cannot differ between fields. All the refusals are one condition at the top, and the local-then-copy shape gives the failure guarantee for free: the capacity line still shows 9F, the last byte of the earlier successful frame. The project's telemetry_encode has the same shape. Day 3 turns to the other direction, reading fields from input that may be too short.

Prove it can fail

After your output matches, swap the two writes in your 16-bit helper so the low octet comes first. The first line becomes 54 01 01 04 00 07 00 FA 00 5B, which is what a little-endian encoder sends, and the hand-derived bytes catch it. Notice the checksum is still 5B: a sum of octets cannot see two octets trade places, which is one reason Day 3 calls a checksum evidence, not proof. Restore the order. Then move the range checks below the memcpy: the rejected 10001 call now overwrites the buffer before reporting failure, and the capacity line says last byte still 99 instead of 9F.

Mistakes worth checking for

  • The length prints as 04 00. The low octet was written first. Big-endian means the most significant octet comes first on the wire.
  • The checksum is wrong by a lot. It included octet 9 itself, or it was computed before the fields were written.
  • Value 10001 is encoded as 27 11. The range check is missing; the wire can hold it, but the specification does not allow it.
  • A rejected call changes the earlier bytes. Something was written to out before every check had passed.
  • Bytes print as FFFFFF80 on some machines. The buffer used plain char, which is signed there, and the negative value was promoted. Use unsigned char and cast to unsigned for %02X.
  • The encoder writes sizeof(Header) bytes from a struct. Padding and the host byte order end up on the wire. Write each octet explicitly.

Was this article helpful?

Your response is saved on this device.