Simvik

Sign-extend a 12-bit sample

Convert a 12-bit two's-complement reading into an int16t. An easy embedded C problem (Integers and data types), run and graded in the browser.

easy · Integers and data types · twos-complement · adc

A sensor returns a signed 12-bit sample in the low 12 bits of a 16-bit word. The upper 4 bits are not part of the sample and may contain anything.

Return the sample as a proper int16_t. For example 0xFFF is -1 and 0x800 is -2048.

Starter code

int16_t sign_extend12(uint16_t raw) {
  // Bits 11..0 hold a two's-complement value; bits 15..12 are junk.
  return 0;
}

Example tests

Largest positive

printf("%d\n", sign_extend12(0x7FF));

Expected output:

2047

Minus one

printf("%d\n", sign_extend12(0xFFF));

Expected output:

-1

Learn it first

More Integers and data types problems