'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 1:[1]

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

Solution 2:[2]

I've adapted this answer

# hex string to signed integer
def htosi(val):
    uintval = int(val, 16)
    bits = 4 * len(val)
    indicative_binary = 2 ** (bits)
    indicative_binary_1 = 2 ** (bits-1)
    if uintval >= indicative_binary_1:
        uintval = int(0 - (indicative_binary - uintval))
    return uintval

This does require a pure hex string:

test1 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877'
print(htosi(test1))

-580140491462537

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 UnoriginalNick
Solution 2 quamrana