Simvik

Saturate to a byte

Narrow a 32-bit value to uint8t by clamping instead of wrapping. An easy embedded C problem (Integers and data types), run and graded in the browser.

easy · Integers and data types · saturation · narrowing

A PWM duty register is 8 bits wide, but the control loop computes its output as an int32_t.

Return v limited to the range 0 to 255. Values below 0 become 0 and values above 255 become 255.

Starter code

uint8_t clamp_u8(int32_t v) {
  // A plain cast would wrap: (uint8_t)300 is 44.
  return (uint8_t)v;
}

Example tests

In range

printf("%u\n", clamp_u8(100));

Expected output:

100

Too large

printf("%u\n", clamp_u8(300));

Expected output:

255

Learn it first

More Integers and data types problems