Simvik

Hearing aid: amplify without wrapping

Apply a fixed-point gain to an audio sample, rounding and saturating instead of wrapping round. A medium embedded C problem (Fixed-point and signal…

medium · Fixed-point and signal processing · q-format · saturation · rounding · product

Product: Hearing aid (Medical)

Requirement. The hearing aid amplifies each 16-bit sample by the wearer's prescribed gain. A loud sound may clip, but it must never wrap round: a wrapped sample is a sharp crack right in the ear.

gain_q8 is unsigned Q8.8: 256 means ×1.0, 512 ×2.0, 384 ×1.5. Return sample × gain, rounded to the nearest integer (halves away from zero) and limited to -32768…32767.

Starter code

int16_t hearing_gain(int16_t s, uint16_t gain_q8) {
  return (int16_t)(s * gain_q8 >> 8);
}

Example tests

Gains of 2 and 1.5

printf("%d %d\n", hearing_gain(1000, 512), hearing_gain(-1000, 384));

Expected output:

2000 -1500

A loud sound clips instead of wrapping

printf("%d %d\n", hearing_gain(20000, 512), hearing_gain(-20000, 512));

Expected output:

32767 -32768

Learn it first

More Fixed-point and signal processing problems