Simvik

Average without overflow

Average two 32-bit values without a wider type. A medium embedded C problem (Integers and data types), run and graded in the browser.

medium · Integers and data types · overflow · bit-tricks

Return the average of a and b, rounded down.

(a + b) / 2 is wrong when the sum does not fit in 32 bits. Solve it using 32-bit arithmetic only.

Starter code

uint32_t avg_u32(uint32_t a, uint32_t b) {
  // (a + b) / 2 overflows when a + b exceeds 4294967295.
  return (a + b) / 2;
}

Example tests

Small values

printf("%u\n", avg_u32(10, 20));

Expected output:

15

Rounds down

printf("%u\n", avg_u32(7, 8));

Expected output:

7

Learn it first

More Integers and data types problems