The project has three source files, and each has exactly one job. Reading them in the order below lets you check every clause of the brief against the line that implements it.
telemetry.his the contract. It declares the opaqueDecoder, theReadingvalue, the allocator callbacks and theFeedResult, and its comments state every pointer precondition and lifetime rule. It also holds the_Static_assertonCHAR_BIT.telemetry.cis the only file that completesstruct Decoder. It owns the 22-byte frame buffer, the encoder and the decoder state machine.main.cis an adapter. It turns hex text into bytes, calls the library, and turns results into output and an exit status. It contains no protocol knowledge at all.
Trace one frame through decoder_feed
Open telemetry.c in the playground at the end of this lesson and find decoder_feed. Its loop copies one byte per iteration into decoder->frame[decoder->used++], then asks three questions at fixed byte counts:
- At
used == 1: is the byte0x54? Garbage input is rejected on its first byte. - At
used == 5: are version and type 1, and is the big-endian length within the 16-byte limit and exactly 4? This runs before any payload byte is stored, which is what keepsusedfrom ever exceeding 10. - At
used == 10: does the checksum match, and are sensor and value in range? Only then are*out = candidate;anddecoder->used = 0;executed, followed by a return withFRAME_READY.
Every rejection goes through the small fail helper, which sets the sticky flag and reports how many bytes were consumed. Notice what is absent: there is no allocation, no pointer kept into bytes, and no write to *out on any path except success. Each absence is a promise from the brief.
The out == NULL || (bytes == NULL && size != 0) check at the top is defensive. Those are precondition violations, and the header says they are not allowed, but turning them into a sticky error is cheaper than debugging a crash. The check does not make passing NULL legal.
Predict and run
Read the program before pressing Run. Predict the number, then explain why the text token 54 means decimal 84 rather than decimal 54.
#include <stdio.h>
int main(void) {
unsigned high = 5, low = 4;
printf("%u\n", high * 16 + low);
return 0;
}Check your prediction
84Each hex digit is worth 16 times the digit to its right, so 54 is 5 times 16 plus 4, which is 84. The token is two characters of text, '5' and '4', and the adapter must turn each character into its digit value before combining them. The character '5' has the code 53 in ASCII, not 5.
How the adapter reads tokens
main.c reads tokens with scanf("%3s", token) into char token[4]. The width 3 is deliberate. A valid token has two characters; reading at most three means a token that is too long, such as 5401, arrives as 540 with a non-null token[2], and the adapter rejects it with "Expected two hex digits per token" instead of silently splitting it into bytes. The fourth array element holds the terminator scanf always writes, so the buffer cannot overflow. Writing %s with no width would let a long token overflow token, which is a classic stack buffer overflow.
The adapter feeds one byte per call. That is the least efficient chunk size, and that is acceptable here because the library's multi-byte behavior is covered by the test suite's partition and chunk-size loops.
One exit path for cleanup
main acquires one resource, the decoder, and has six ways to fail. It uses the single-exit shape you already know from C Intermediate's cleanup lesson: exit_code = 1 at the start, goto cleanup; on every failure, exit_code = 0 only at the end of the success path, and one cleanup: block that releases everything. The decoder is created before the first goto, so decoder_destroy always receives a valid handle; had it been created later, the variable would need to start as NULL, which destroy accepts. Open main.c in the download and count the paths that reach cleanup:.
Two checks are easy to forget. The adapter tests ferror(stdin) after the loop, so a read error is not mistaken for end of input, and ferror(stdout) before exiting, so a failed write is not reported as success. Errors go to standard error and readings to standard output, so a script can capture readings separately.
Practice
Your turn
Write int hex_digit(int ch) returning 0 to 15 or -1, and int parse_token(const char *token, unsigned char *out) returning 0 for a byte, 1 for a bad digit and 2 for a token that is not exactly two characters. *out changes only on success. Run the tokens in the starter and print:
54: byte 84
ff: byte 255
0A: byte 10
G1: invalid hex token
5: expected two hex digits
540: expected two hex digits#include <stdio.h>
int main(void) {
const char *tokens[6] = {"54", "ff", "0A", "G1", "5", "540"};
unsigned char byte = 0;
/* Write hex_digit and parse_token above, then print one line per token. */
(void)tokens; (void)byte;
return 0;
}Hint 1: the idea
Check the length first, using the same three-character test as main.c: token[0], token[1] and token[2] tell you whether the token has fewer than, exactly, or more than two characters. Only then look at the digits.
Hint 2: a first step
Write the length test first, and print a verdict for "7", "7f" and "7f0". The characters at indexes 0, 1 and 2 decide it, and the order you test them in decides whether you ever read past the end. Write hex_digit after that, one range at a time.
Show one solution
#include <stdio.h>
int hex_digit(int ch) {
if (ch >= '0' && ch <= '9') { return ch - '0'; }
if (ch >= 'a' && ch <= 'f') { return ch - 'a' + 10; }
if (ch >= 'A' && ch <= 'F') { return ch - 'A' + 10; }
return -1;
}
int parse_token(const char *token, unsigned char *out) {
if (token[0] == '\0' || token[1] == '\0' || token[2] != '\0') { return 2; }
int high = hex_digit(token[0]), low = hex_digit(token[1]);
if (high < 0 || low < 0) { return 1; }
*out = (unsigned char)(high * 16 + low);
return 0;
}
int main(void) {
const char *tokens[6] = {"54", "ff", "0A", "G1", "5", "540"};
const char *errors[3] = {"", "invalid hex token", "expected two hex digits"};
unsigned char byte = 0;
for (size_t i = 0; i < 6; ++i) {
int result = parse_token(tokens[i], &byte);
if (result == 0) { printf("%s: byte %u\n", tokens[i], (unsigned)byte); }
else { printf("%s: %s\n", tokens[i], errors[result]); }
}
return 0;
}54: byte 84
ff: byte 255
0A: byte 10
G1: invalid hex token
5: expected two hex digits
540: expected two hex digitsReturning -1 from hex_digit keeps "invalid" distinct from the digit 0, which a return value of 0 could not do. The 'a' to 'f' range test relies on those letters having consecutive codes. That holds in ASCII and every encoding a modern compiler uses, though the C standard guarantees consecutive codes only for the digits '0' to '9'. The same checks sit at the top of the loop in main.c, below.
Run the decoder application
Check your prediction
Sensor 1: 25
Sensor 2: 40
Frames: 2Now run the acceptance cases from the brief by editing the input. Clear it completely and confirm Frames: 0. Restore the sample and delete its final 84 to see "Truncated frame" after the first reading. Restore it again and change the first frame's checksum from 74 to 75: the error appears before any reading is printed, because the bad frame comes first. Then put GG at the start and check that the adapter rejects it before the library sees a byte.
Completion is saved in this browser only. It does not measure mastery.