2

I just started working with hexadecimal values in python and am a bit surprised with what I just encountered. I expected the following code to first print a hexadecimal string, and then a decimal value.

Input:

n = 0x8F033CAE74F88BA10D2BEA35FFB0EDD3
print('Hex value for n is:', n)
print('Dec value for n is:', int(str(n), 16))

Output:

Hex value for n is: 190096411054295805012706659640261275091

Dec value for n is: 8921116140846515089057635273465667902228615313

How is it possible that 2 different different numbers are shown? I expected the first number to be a hexadecimal string and the second it's decimal equivalent, what is this second value in this case?

1 Answer 1

7

0x is a way to input an integer with an hexadecimal notation.

>>> n = 0x8F033CAE74F88BA10D2BEA35FFB0EDD3

This hexadecimal notation is forgotten directly after instantiation, though:

>>> n
190096411054295805012706659640261275091
>>> str(n)
'190096411054295805012706659640261275091'

So when you call int(str(n), 16), Python interprets '190096411054295805012706659640261275091' as an hexadecimal number:

>>> int(str(n), 16)
8921116140846515089057635273465667902228615313

You need to input the original hex string:

>>> int("8F033CAE74F88BA10D2BEA35FFB0EDD3", 16)
190096411054295805012706659640261275091

or use hex:

>>> int(hex(n), 16)
190096411054295805012706659640261275091
Sign up to request clarification or add additional context in comments.

3 Comments

Thus, I guess, the second output is the decimal, interpreted as hexadecimal (digit by digit), and converted back to decimal. Hence the even bigger number. Am I right?
@Scheff: Exactly.
I tried to reproduce on my calculator but the numbers have to many digits... ;-)

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.