Skip to main content
 首页 » 编程设计

Python hex 到 int 转换错误

2025年05月04日18lhb25

>>> print(int(0x51)) 

81

这是正确的。

>>> str = 51 
>>> cmd = "0x%s" %(str) 
>>> print(int(cmd)) 

但为什么这是不正确的呢? 我得到 ValueError: invalid literal for int() with base 10: '0x51'

请您参考如下方法:

0x51 是一个 Python 整数文字,它本身已经产生一个整数:

>>> 0x51 
81 

参见 Integer and long integer literals documentation详情;这是 hexinteger 形式。对该整数对象调用 int() 只会再次返回相同的整数值。

您可以对前缀为0x的字符串使用int(),但您需要告诉它使用0 作为基础:

>>> int('0x51', 0) 
81 

0 是这里的特例;它告诉 int() 寻找 Python 整数文字前缀,例如 0x 以确定真正的基础。来自int() documenation :

Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16.