</>EmbeddedInterview
← All problems · Bit Manipulation

Sign Extend a 12-bit ADC Sample

Medium

Interpret the low 12 bits as a signed two's-complement sample; ignore upper bits. Implement int32_t adc_signed(uint16_t x).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Subtract 4096 for values with bit 11 set.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>

int32_t adc_signed(uint16_t x)
{
    int32_t v=x & 0xfff; return v>=2048 ? v-4096 : v;
}

The subtraction produces the signed value without implementation-defined signed shifts.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    
    CHECK(adc_signed(0)==0);
    CHECK(adc_signed(0x7ff)==2047);
    CHECK(adc_signed(0x800)==-2048);
    CHECK(adc_signed(0xffff)==-1);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}