Python hex()

Python hex() 函数被用来将整数转换为以0x为前缀的低级六十字符串。我们还可以将一个对象传递给 hex() 函数,在这种情况下,对象必须具有定义的 __index__() 函数,返回整数。

Python hex() 示例

让我们看看将整数转换为六进制数的几个简单例子。

1print(hex(255))  # decimal
2print(hex(0b111))  # binary
3print(hex(0o77))  # octal
4print(hex(0XFF))  # hexadecimal

输出:

10xff
20x7
30x3f
40xff

Python hex() 与对象

让我们创建一个自定义的 [类]( / 社区 / 教程 / Python - 类 - 对象)并定义 index() 函数,以便我们可以使用 hex() 函数。

 1class Data:
 2    id = 0
 3
 4    def __index__(self):
 5        print('__index__ function called')
 6        return self.id
 7
 8d = Data()
 9d.id = 100
10
11print(hex(d))

输出:

1__index__ function called
20x64

您可以从我们的 GitHub 存储库中查阅完整的 Python 脚本和更多 Python 示例。

参考: 官方文件

Published At
Categories with 技术
Tagged with
comments powered by Disqus