Python的hex()函数用于将整数转换为以“0x”为前缀的小写十六进制字符串。我们也可以将对象传递给hex()函数,在这种情况下,对象必须定义__index__()函数,该函数返回整数。输入整数参数可以是任何基数,如二进制、八进制等。Python将负责将它们转换为十六进制格式。
Python hex()示例
让我们看一些将整数转换为十六进制数的简单示例。
print(hex(255)) # decimal
print(hex(0b111)) # binary
print(hex(0o77)) # octal
print(hex(0XFF)) # hexadecimal
输出:
0xff
0x7
0x3f
0xff
Python hex()与对象
让我们创建一个自定义类并定义__index__()函数,以便我们可以与其一起使用hex()函数。
class Data:
id = 0
def __index__(self):
print('__index__ function called')
return self.id
d = Data()
d.id = 100
print(hex(d))
输出:
__index__ function called
0x64
您可以从我们的GitHub存储库中查看完整的Python脚本和更多Python示例。
参考:官方文档
Source:
https://www.digitalocean.com/community/tutorials/python-hex