0

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
Kaleb
  • 25
  • 1
  • 4
  • Do the answers to this [question](https://stackoverflow.com/questions/6727875/hex-string-to-signed-int-in-python-3-2) help at all? – quamrana Mar 24 '22 at 14:38
  • Yeah i tried `twos_complement` and the other suggestions, they all led to that long numbered answer... I think it's related to how negative integers are in hexstr form – Kaleb Mar 24 '22 at 14:40
  • 1
    It's important to note that the answer you're getting isn't wrong, it's just that the default representation that Python is using isn't the same as the one you're trying to use. If you're doing this for educational purposes, one of the things that this lesson is trying to teach is the difference between the representation of a value and the value itself. – Patrick Haugh Mar 24 '22 at 14:58

2 Answers2

3

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
UnoriginalNick
  • 327
  • 1
  • 3
1

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
quamrana
  • 37,849
  • 12
  • 53
  • 71