Simvik

Fix: below zero, the freezer reads 255 °C

A 12-bit two's-complement reading is widened without its sign. A medium embedded C problem (Integers and data types), run and graded in the browser.

medium · Integers and data types · find-the-bug · sign-extension · twos-complement

Bug report. The freezer's temperature sensor returns a 12-bit two's-complement value in the low 12 bits of a 16-bit register, in units of 1/16 °C; the top four bits are undefined. temp_sixteenths(raw) should return that signed value. Above zero it is right, but as soon as the freezer goes below zero, -0.0625 °C comes back as 4095 sixteenths, 255.9 °C, and the alarm goes off. Fix it by changing one line.

Starter code

int16_t temp_sixteenths(uint16_t raw) {
  int16_t v = raw & 0x0FFF;
  return v;
}

Example tests

Room temperature, then just below zero

printf("%d %d %d\n", temp_sixteenths(0x0190), temp_sixteenths(0x0FFF), temp_sixteenths(0x0C90));

Expected output:

400 -1 -880

Learn it first

More Integers and data types problems