Search code examples
pythonintegersigned

Converting hexstr to signed integer - Python


I have this hexstr 0xfffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877, in decimal terms it should give -580140491462537. However doing the below leads to bad answers. Can someone help?

In: test = '0xfffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877'
In: int(test,16)
Out: 11579208923731619542357098500868790785326998466564056403945758342777263817739

Solution

  • First convert the string to bytes. You'll have to remove the leading "0x". Then use int.from_bytes and specify that it's signed and big-endian.

    In: int.from_bytes(bytes.fromhex(test[2:]), byteorder="big", signed=True)
    Out: -580140491462537