Search code examples
c#monointegerdata-conversiontwos-complement

Convert 24 bit two's complement to int?


I have a C#/Mono app that reads data from an ADC. My read functions returns it as ulong. The data is in two complement and I need to translate it into int. E.g.:

0x7FFFFF = + 8,388,607
0x7FFFFE = + 8,388,606
0x000000 = 0
0xFFFFFF = -1
0x800001 = - 8,388,607
0x800000 = - 8,388,608

How can I do this?


Solution

  • const int MODULO = 1 << 24;
    const int MAX_VALUE = (1 << 23) - 1;
    
    int transform(int value) {
      if (value > MAX_VALUE) {
        value -= MODULO;
      }
      return value;
    }
    

    Explanation: MAX_VALUE is the maximum possible positive value that can be stored in 24 signed int, so if the value is less or equal then that, it should be returned as is. Otherwise value is unsigned representation of two-complement negative number. The way two-complement works is that negative number is written as a number modulo MODULO, which would effectively mean that MODULO is added. So to convert it back to signed we subtract MODULO.