📜  Python hex()

📅  最后修改于: 2020-09-20 04:10:00             🧑  作者: Mango

hex() 函数将整数转换为相应的十六进制字符串。

hex()的语法为:

hex(x)

hex()参数

hex() 函数采用单个参数。

x-整数( int对象,或者它必须定义返回整数的__index__()方法)

从hex()返回值

hex() 函数将整数转换为字符串形式的相应十六进制数,然后将其返回。

返回的十六进制字符串以前缀0x表示它为十六进制格式。

示例1:hex()如何工作?

number = 435
print(number, 'in hex =', hex(number))

number = 0
print(number, 'in hex =', hex(number))

number = -34
print(number, 'in hex =', hex(number))

returnType = type(hex(number))
print('Return type from hex() is', returnType)

输出

435 in hex = 0x1b3
0 in hex = 0x0
-34 in hex = -0x22
Return type from hex() is 

如果需要查找浮点数的十六进制表示形式,则需要使用float.hex()方法。

示例2:浮点数的十六进制表示

number = 2.5
print(number, 'in hex =', float.hex(number))

number = 0.0
print(number, 'in hex =', float.hex(number))

number = 10.5
print(number, 'in hex =', float.hex(number))

输出

2.5 in hex = 0x1.4000000000000p+1
0.0 in hex = 0x0.0p+0
10.5 in hex = 0x1.5000000000000p+3