4

I have a file with HEX data I want to convert it into SIGNED DECIMAL using python. int('0xffd2',16) is not the solution since it converts the HEX to unsigned DEC. Any idea how to do it?

0xffd2, 65490

0xffcb, 65483

0xffcb, 65483

0xffcc, 65484

0x10, 16

0xc, 12

0xd, 13

0x0, 0

0xfffe, 65534
hmatt1
  • 4,939
  • 3
  • 30
  • 51
Dody
  • 187
  • 2
  • 2
  • 5

2 Answers2

13

You can interpret the bytes as a two's complement signed integer using bitwise operations. For example, for a 16-bit number:

def s16(value):
    return -(value & 0x8000) | (value & 0x7fff)

Therefore:

>>> s16(int('0xffd2', 16))
-46
>>> s16(int('0xffcb', 16))
-53
>>> s16(int('0xffcc', 16))
-52
>>> s16(int('0x10', 16))
16
>>> s16(int('0xd', 16))
13
>>> s16(int('0x0', 16))
0
>>> s16(int('0xfffe', 16))
-2

This can be extended to any bit-length string, by setting the masks so the first mask matches the most-significant bit (0x8000 == 1 << 15 == 0b1000000000000000) and the second mask matches the all the remaining bits (0x7fff == (1 << 15) - 1 == 0b0111111111111111).

dcoles
  • 3,785
  • 2
  • 28
  • 26
6

Once you have the unsigned value, it's very easy to convert to signed.

if value >= 0x8000:
    value -= 0x10000

This is for a 16-bit number. For a 32-bit number just add 4 zeros to each of the magic constants. Those constants can also be calculated as 1 << (bits - 1) and 1 << bits.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622