简体   繁体   English

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

[英]Converting hexadecimal value to decimal in Python

I just started working with hexadecimal values in python and am a bit surprised with what I just encountered. 我刚刚开始使用python中的十六进制值,我对刚刚遇到的内容感到有些惊讶。 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 n的十六进制值是:190096411054295805012706659640261275091

Dec value for n is: 8921116140846515089057635273465667902228615313 n的Dec值为:8921116140846515089057635273465667902228615313

How is it possible that 2 different different numbers are shown? 如何显示2个不同的不同数字? 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? 我期望第一个数字是十六进制字符串,第二个数字是十进制等效数,在这种情况下,第二个值是多少?

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 : 或使用hex

>>> int(hex(n), 16)
190096411054295805012706659640261275091

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM