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.

3 Answers 3

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,)
Sign up to request clarification or add additional context in comments.

1 Comment

Or struct.unpack('>q', bytearray.fromhex('b69958096aff3148'))
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.