如何使用Python中的ascii转换将十六进制值转换为整数?
我需要将十六进制数转换成整数 我有n=2,然后使用newN=hexn,它给了我0x32的值。现在我尝试使用intnewN,16将其重新转换为整数值,但这并没有给我任何东西,它只给了我一个空字符串。 我也试过chrintnewN,16岁,但结果相同 这是一个测试代码如何使用Python中的ascii转换将十六进制值转换为整数?,python,hex,ascii,Python,Hex,Ascii,我需要将十六进制数转换成整数 我有n=2,然后使用newN=hexn,它给了我0x32的值。现在我尝试使用intnewN,16将其重新转换为整数值,但这并没有给我任何东西,它只给了我一个空字符串。 我也试过chrintnewN,16岁,但结果相同 这是一个测试代码 n = '2' newN = hex(n) print(str(newN)) oldN = chr(int(newN, 16)) print(str(oldN)) 我得到以下信息: 0x32 首先,您的问题是不正确的n变量的类型是
n = '2'
newN = hex(n)
print(str(newN))
oldN = chr(int(newN, 16))
print(str(oldN))
我得到以下信息:
0x32
首先,您的问题是不正确的n变量的类型是长度为1的stringn,而不是整数。因为它对应于十六进制值50,相当于ASCII中的“2” 代码:- 输出:-
对不起,是的。n是一个字符串。那么我如何从0x32得到50,才能得到我需要的2呢;chr50='2'我确实尝试过,但结果仍然是空字符串,不知道为什么。您的代码运行良好,只需在第2行将hexn更改为hexordn即可。
n = '2'
# Ord(n) gives us the Unicode code point of the given character ('2' = 50)
# hex() produces its hexadecimal equivalent (50 = "0x32")
n_hex = hex(ord(n))
# 0x32
print(n_hex)
# Ord(n) gives us the Unicode code point of the given character ('2' = 50)
n_hex_int = ord(n)
# 50
print(n_hex_int)
0x32
50