如何在 python 中使用 hex()?
How to work with hex() in python?
我在 python 2.7 中遇到 hex() 问题
我想通过用户输入将“0777”转换为十六进制。
但它在用户输入中使用整数有问题。
In [1]: hex(0777)
Out[1]: '0x1ff'
In [2]: hex(777)
Out[2]: '0x309'
In [3]: z = raw_input('enter:')
enter:0777
In [4]: z
Out[4]: '0777'
In [5]: hex(z)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-3682d79209b9> in <module>()
----> 1 hex(z)
TypeError: hex() argument can't be converted to hex
In [6]: hex(int(z))
Out[6]: '0x309'
In [7]:
我需要 0x1ff,但显示的是 0x309,我该如何解决?
base参数int
class默认为10
int(x, base=10) -> integer
前导零将被去除。看这个例子:
In [1]: int('0777')
Out[1]: 777
明确指定以 8 为基数,然后 hex
函数将为您提供所需的结果:
In [2]: hex(int('0777', 8))
Out[2]: '0x1ff'
您可以使用 input()
而不是 raw_input() 来评估输入和读取八进制值。
In [3]: z = input('enter:')
enter:0777
In [4]: z
Out[4]: 511
In [5]: hex(z)'
Out[5]: '0x1ff'
我在 python 2.7 中遇到 hex() 问题 我想通过用户输入将“0777”转换为十六进制。 但它在用户输入中使用整数有问题。
In [1]: hex(0777)
Out[1]: '0x1ff'
In [2]: hex(777)
Out[2]: '0x309'
In [3]: z = raw_input('enter:')
enter:0777
In [4]: z
Out[4]: '0777'
In [5]: hex(z)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-3682d79209b9> in <module>()
----> 1 hex(z)
TypeError: hex() argument can't be converted to hex
In [6]: hex(int(z))
Out[6]: '0x309'
In [7]:
我需要 0x1ff,但显示的是 0x309,我该如何解决?
base参数int
class默认为10
int(x, base=10) -> integer
前导零将被去除。看这个例子:
In [1]: int('0777')
Out[1]: 777
明确指定以 8 为基数,然后 hex
函数将为您提供所需的结果:
In [2]: hex(int('0777', 8))
Out[2]: '0x1ff'
您可以使用 input()
而不是 raw_input() 来评估输入和读取八进制值。
In [3]: z = input('enter:')
enter:0777
In [4]: z
Out[4]: 511
In [5]: hex(z)'
Out[5]: '0x1ff'