>> print(int(cmd)) 但为什么这是不正确的呢?-6ren">
gpt4 book ai didi

Python hex 到 int 转换错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:23 25 4
gpt4 key购买 nike

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

关于Python hex 到 int 转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32192467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com