0

I have a hex string, for instance: 0xb69958096aff3148

And I want to convert this to a signed integer like: -5289099489896877752

In Python, if I use the int() function on above hex number, it returns me a positive value as shown below:

>>> int(0xb69958096aff3148)
13157644583812673864L

However, if I use the "Hex" to "Dec" feature on Windows Calculator, I get the value as: -5289099489896877752

And I need the above signed representation.

For 32-bit numbers, as I understand, we could do the following:

struct.unpack('>i', s)

How can I do it for 64-bit integers?

Thanks.

Neon Flash
  • 3,113
  • 12
  • 58
  • 96

3 Answers3

4

If you want to convert it to 64-bit signed integer then you can still use struct and pack it as unsigned integer ('Q'), then unpack as signed ('q'):

>>> struct.unpack('<q', struct.pack('<Q', int('0xb69958096aff3148', 16)))
(-5289099489896877752,)
a_guest
  • 34,165
  • 12
  • 64
  • 118
2

I would recommend the bitstring package available through conda or pip.

from bitstring import BitArray
b = BitArray('0xb69958096aff3148')
b.int
# returns
-5289099489896877752

Want the unsigned int?:

b.uint
# returns:
13157644583812673864
James
  • 32,991
  • 4
  • 47
  • 70
1

You could do a 64-bit version of this, for example:

def signed_int(h):
    x = int(h, 16)
    if x > 0x7FFFFFFFFFFFFFFF:
        x -= 0x10000000000000000
    return x


print(signed_int('0xb69958096aff3148'))

Output

-5289099489896877752
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76