Two kinds of arithmetic show up in every decoder. Bit arithmetic pulls fields out of bytes and puts them back: shifts move bits into position and masks keep only the ones you want. Bounds arithmetic decides whether a read stays inside the buffer. Both look trivial, and both have edge cases where C's rules turn a one-line expression into undefined behavior or a silent security hole. This lesson collects those rules in one place before Day 3 builds a cursor on top of them.
The project needs a few concrete numbers. The header is five octets, the payload limit is sixteen, and the checksum is one octet, so the internal frame buffer holds 22 bytes. The checksum keeps only the low eight bits of a sum, which is a mask by 255.
Predict and run
Read the program before pressing Run. Write down its output and say which operator produces each number.
#include <stdio.h>
int main(void) {
unsigned long value = 0x1234UL;
printf("%lu %lu\n", value >> 8, value & 255UL);
return 0;
}Check your prediction
18 520x1234 >> 8 drops the low eight bits and leaves 0x12, which is 18. 0x1234 & 255 keeps only the low eight bits, 0x34, which is 52. The shift chooses which bits move into the low position; the mask chooses which bits survive. They are independent tools, which is why encoding a two-octet field takes one of each.
Pull fields out of a byte
Masks also work inside a single byte. Suppose a status octet packs three facts: bit 7 is an alarm flag, bits 4 to 6 are a priority, and bits 0 to 3 are a channel. Shift the field down to bit 0, then mask to its width:
#include <stdio.h>
int main(void) {
const unsigned char status = 0xB6; /* 1011 0110 */
unsigned alarm = (status >> 7) & 0x1u;
unsigned priority = (status >> 4) & 0x7u;
unsigned channel = status & 0xFu;
printf("alarm %u, priority %u, channel %u\n", alarm, priority, channel);
unsigned rebuilt = (alarm << 7) | (priority << 4) | channel;
printf("rebuilt %02X\n", rebuilt);
return 0;
}alarm 1, priority 3, channel 6
rebuilt B6Every constant has a u suffix and every operand is unsigned. That habit matters because of three C rules:
- Shift counts must be in range. Shifting by a negative count, or by at least the width of the promoted type, is undefined.
1u << 32on a 32-bitunsignedis not 0; it is undefined, and x86 hardware actually computes1u << 0for it. - Signed left shifts can overflow.
1 << 31on a 32-bitintis undefined.1u << 31is fine. - Right-shifting a negative value is implementation-defined. Most compilers copy the sign bit in, so
-16 >> 2is -4, but the standard does not promise it. Unsigned right shifts always fill with zeros.
Bit operations also give no permission to read past a buffer. Extracting bit 3 of bytes[10] from a ten-byte array is still an out-of-bounds read.
Unsigned wraparound is defined, and still dangerous
Unsigned arithmetic in C never overflows in the undefined sense. It wraps modulo 2 to the power of the width: SIZE_MAX + 1 is 0. Signed overflow, by contrast, is undefined, which lets optimizers assume i + 1 > i for a signed i. The unsigned rule sounds safer, but it creates a classic bounds bug. A check that adds first can wrap to a small number and pass:
#include <stdio.h>
#include <stdint.h>
int naive_fits(size_t position, size_t length, size_t requested) {
return position + requested <= length; /* the sum can wrap */
}
int safe_fits(size_t position, size_t length, size_t requested) {
return position <= length && requested <= length - position;
}
int main(void) {
size_t length = 10, position = 4, requested = SIZE_MAX - 1;
printf("naive: %s\n", naive_fits(position, length, requested) ? "fits" : "rejected");
printf("safe: %s\n", safe_fits(position, length, requested) ? "fits" : "rejected");
return 0;
}naive: fits
safe: rejected4 + (SIZE_MAX - 1) wraps around to 2, and 2 is less than 10, so the naive check approves a read of nearly the whole address space. If requested comes from an attacker-controlled length field, that is a buffer overflow waiting to happen.
The safe form never adds. It first proves position <= length, and only then computes length - position, which therefore cannot wrap. The && operator evaluates left to right and stops at the first false operand, so the subtraction never runs on an invalid position. That ordering is the whole technique: establish the fact that makes the next expression safe, then use it.
Practice
Your turn
A frame often carries a table: a count field followed by that many fixed-size records. The bytes needed are count * record_size, and that product can wrap just like the sum above. Write int records_fit(size_t position, size_t length, size_t count, size_t record_size) that answers "do count records of record_size bytes fit between position and length?" without adding or multiplying sizes. A zero record_size is rejected. Run it on the six cases in the starter and print:
pos 2 len 14 count 3 size 4: fits
pos 2 len 14 count 4 size 4: rejected
pos 14 len 14 count 0 size 4: fits
pos 15 len 14 count 0 size 4: rejected
pos 0 len 14 count huge size 4: rejected
pos 0 len 14 count 1 size 0: rejected#include <stdio.h>
#include <stdint.h>
int main(void) {
const size_t huge = SIZE_MAX / 2 + 1;
const size_t cases[6][4] = {
{2, 14, 3, 4}, {2, 14, 4, 4}, {14, 14, 0, 4}, {15, 14, 0, 4}, {0, 14, SIZE_MAX / 2 + 1, 4}, {0, 14, 1, 0},
};
/* Write records_fit above, then print one line per case. Print "huge" for the huge count. */
(void)huge; (void)cases;
return 0;
}Hint 1: the idea
safe_fits avoided an addition by turning it into a subtraction that was already known to be safe. Do the same with the multiplication: turn it into an operation on the space that is left, which cannot overflow once you know the position is in range and the record size is not zero.
Hint 2: a first step
Write the obvious return position <= length && count * record_size <= length - position; first and run it. The huge line says fits: (SIZE_MAX / 2 + 1) * 4 wraps to 0. Keep the position check and replace only the comparison that multiplies.
Show one solution
#include <stdio.h>
#include <stdint.h>
/* Do count records of record_size bytes each fit in [position, length)?
A zero record size is rejected. Never adds or multiplies sizes. */
int records_fit(size_t position, size_t length, size_t count, size_t record_size) {
if (record_size == 0 || position > length) { return 0; }
return count <= (length - position) / record_size;
}
int main(void) {
const size_t huge = SIZE_MAX / 2 + 1;
const size_t cases[6][4] = {
{2, 14, 3, 4}, {2, 14, 4, 4}, {14, 14, 0, 4}, {15, 14, 0, 4}, {0, 14, SIZE_MAX / 2 + 1, 4}, {0, 14, 1, 0},
};
for (size_t i = 0; i < 6; ++i) {
const size_t *c = cases[i];
printf("pos %zu len %zu count ", c[0], c[1]);
if (c[2] == huge) { printf("huge"); } else { printf("%zu", c[2]); }
printf(" size %zu: %s\n", c[3], records_fit(c[0], c[1], c[2], c[3]) ? "fits" : "rejected");
}
return 0;
}pos 2 len 14 count 3 size 4: fits
pos 2 len 14 count 4 size 4: rejected
pos 14 len 14 count 0 size 4: fits
pos 15 len 14 count 0 size 4: rejected
pos 0 len 14 count huge size 4: rejected
pos 0 len 14 count 1 size 0: rejected(length - position) / record_size is how many whole records fit in the space left, so comparing count with it never forms the product. Integer division rounds down, which is exactly right: a partial record does not fit. The zero check comes first because dividing by zero is undefined, and a zero-size record has no sensible meaning in a wire format anyway. The position check still comes before the subtraction, as in safe_fits. The checkpoint next uses these pieces to encode a complete frame header by hand.
Completion is saved in this browser only. It does not measure mastery.