Simvik

Unsigned difference

Return the distance between two unsigned values without wrapping. An easy embedded C problem (Integers and data types), run and graded in the browser.

easy · Integers and data types · unsigned · underflow

Two unsigned sensor readings can arrive in either order. Return how far apart they are.

a - b on unsigned values wraps to a huge number when b is larger, so subtract in the right direction.

Starter code

uint32_t abs_diff(uint32_t a, uint32_t b) {
  // Return |a - b| without ever producing a wrapped result.
  return 0;
}

Example tests

First is larger

printf("%u\n", abs_diff(10, 3));

Expected output:

7

Second is larger

printf("%u\n", abs_diff(3, 10));

Expected output:

7

Learn it first

More Integers and data types problems