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
3
  • Do the answers to this question help at all? Commented Mar 24, 2022 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 Commented Mar 24, 2022 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. Commented Mar 24, 2022 at 14:58

2 Answers 2

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

Comments

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

1 Comment

thank you for your help, really appreciate it

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.