如何用Python中的ascii转换将十六进制值转换成整数?

2024-09-22 16:40:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要把十六进制数转换成整数。你知道吗

我有n=2,然后使用newN=hex(n),它给了我值0x32。现在我试图用int(newN,16)将它重新转换为整数值,但这并没有给我什么,它只给了我一个空字符串。 我也试过chr(int(newN,16)),但结果是一样的。你知道吗

这是一个测试代码

n = '2'
newN = hex(n)
print(str(newN))
oldN = chr(int(newN, 16))
print(str(oldN))

我得到以下信息:

0x32

Tags: 字符串信息整数intprinthex测试代码str
1条回答
网友
1楼 · 发布于 2024-09-22 16:40:00

首先你的问题是不正确的n变量的类型是字符串(长度为1),而不是整数。(因为它对应于十六进制值50,相当于ASCII中的“2”)

代码:-

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

相关问题 更多 >