Python hex() 函数用于将整数转换为十六进制 (base-16) 格式。
十六进制是一种使用 16 位数字的数字系统,其中前 10 位与十进制系统 (0-9) 相同,接下来的 6 位由字母 A 到 F(或 a-f)表示,对应于值 10 到 15。当您在 Python 中使用 hex() 函数时,它会将十进制数转换为其十六进制表示形式,结果是一个以“0x”开头,后跟十六进制数字的字符串。
语法
以下是 python hex() 函数的语法 -
参数
此函数接受整数值作为其参数。
返回值
此函数返回一个字符串,该字符串表示给定整数的十六进制值。
示例 1以下是 Python hex() 函数的示例。在这里,我们将整数 “111” 转换为其十六进制表示 -
输出
以下是上述代码的输出 -
The hexadecimal value obtained is: 0x6f
示例 2
在这里,我们使用 hex() 函数将二进制和八进制值转换为它们相应的十六进制表示 -
输出
获得的输出如下 -
The hexadecimal value of binary number is: 0xa
The hexadecimal value of octal number is: 0x3f
The hexadecimal value of octal number is: 0x3f
示例 3
现在,当使用 hex() 函数将整数值 “2108” 转换为其十六进制表示时,我们从输出中删除 “0x” 前缀 -
输出
生成的结果如下 -
The hexadecimal value of the integer without prefix is: 83c
示例 4
如果我们将非整数值传递给 hex() 函数,它将引发 TypeError。
在这里,我们将通过将浮点值 “11.21” 传递给 hex() 函数来演示 TypeError -
输出
我们可以在输出中看到我们得到一个 TypeError,因为我们把一个浮点值传递给了 hex() 函数 -
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
hexadecimal_number = hex(floating_number)
TypeError: 'float' object cannot be interpreted as an integer
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
hexadecimal_number = hex(floating_number)
TypeError: 'float' object cannot be interpreted as an integer
示例 5
由于十六进制以 16 为基数表示法表示数字,因此我们可以使用 float.hex() 函数而不是常规 hex() 函数来处理 TypeError。
输出
代码的输出如下 -
The hexadecimal value of the floating number is: 0x1.66b851eb851ecp+3