在Python中将十六进制值转换为十进制

时间:2022-03-14 17:14:48

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.

我刚刚开始在python中使用十六进制值,我对刚刚遇到的内容感到有些惊讶。我期望以下代码首先打印十六进制字符串,然后是十进制值。

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

n的十六进制值是:190096411054295805012706659640261275091

Dec value for n is: 8921116140846515089057635273465667902228615313

n的Dec值为: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?

如何显示2个不同的数字?我期望第一个数字是十六进制字符串,第二个数字是十进制等效数字,在这种情况下,第二个值是多少?

1 个解决方案

#1


7  

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

0x是一种使用十六进制表示法输入整数的方法。

>>> 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)时,Python将'190096411054295805012706659640261275091'解释为十六进制数:

>>> 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

#1


7  

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

0x是一种使用十六进制表示法输入整数的方法。

>>> 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)时,Python将'190096411054295805012706659640261275091'解释为十六进制数:

>>> 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