Neon Flash
Neon Flash

Reputation: 3233

Python convert Hex string to Signed Integer

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.

Upvotes: 0

Views: 5131

Answers (3)

a_guest
a_guest

Reputation: 36249

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,)

Upvotes: 4

James
James

Reputation: 36608

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

Upvotes: 2

Dani Mesejo
Dani Mesejo

Reputation: 61910

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

Upvotes: 1

Related Questions