Simvik

Apply a function to a buffer

Transform every element of an array with a caller-supplied function. An easy embedded C problem (Function pointers and state machines), run and graded in the…

easy · Function pointers and state machines · callbacks

Replace each of the n bytes at data with the result of calling fn on it. If fn is NULL, leave the data unchanged.

Starter code

void map_u8(uint8_t *data, size_t n, uint8_t (*fn)(uint8_t)) {
  // data[i] = fn(data[i]) for every element.
}

Example tests

Invert every byte

uint8_t d[] = { 0x00, 0x0F, 0xFF };
map_u8(d, 3, invert);
printf("%02X %02X %02X\n", d[0], d[1], d[2]);

Expected output:

FF F0 00

Halve every byte

uint8_t d[] = { 10, 7, 255 };
map_u8(d, 3, half);
printf("%u %u %u\n", d[0], d[1], d[2]);

Expected output:

5 3 127

Learn it first

More Function pointers and state machines problems