Simvik

Float to Q16.16, rounded and saturated

Convert a float to Q16.16 fixed point, to the nearest step, clamped to the range. An easy embedded C problem (Floating point on the Cortex-M33), run and…

easy · Floating point on the Cortex-M33 · float · fixed-point

A Pico 2 works out a control gain in float and hands it to code that runs in Q16.16 fixed point: the value times 65536 in an int32_t.

Return v in Q16.16, rounded to the nearest step (halves away from zero) and saturated: values from 32768.0 up give INT32_MAX, values below -32768.0 give INT32_MIN. Casting a float that does not fit to an integer is undefined behaviour in C, so check the range first.

Starter code

int32_t float_to_q16(float v) {
  // Truncates towards zero and overflows outside the range.
  return (int32_t)(v * 65536.0f);
}

Example tests

Whole numbers and fractions

printf("%ld %ld %ld\n", (long)float_to_q16(1.0f), (long)float_to_q16(0.5f), (long)float_to_q16(-2.25f));

Expected output:

65536 32768 -147456

Rounding to the nearest step

printf("%ld %ld\n", (long)float_to_q16(0.8f), (long)float_to_q16(-0.8f));

Expected output:

52429 -52429

Learn it first

More Floating point on the Cortex-M33 problems