Search code examples
darthexdecimal

Flutter - Convert Hexadecimal to Decimal signed 2's compliment


I'm trying to convert the hex value to decimal and I was able to convert it using int.parse('8E', radix: 16), but I'm not able to get the decimal from signed 2's complement. If you convert 8E(hex): What I'm getting from this int.parse('8E', radix: 16) is 142. What I want is -114

please use this converter for reference - https://www.rapidtables.com/convert/number/hex-to-decimal.html

Can somone help me to get the decimal from signed 2's complement?


Solution

  • Your issue is that int.parse returns a 64-bit signed integer and your hex value represent a signed 8-bit value.

    By doing a "bit" of bit-shifting, we can convert the value so the numeric value are the same as the 8-bit value represented:

    void main() {
      int value = (int.parse('8E', radix: 16) << 56) >> 56;
      print(value); // -114
    }