如何将python HEX输出转换为ASCII?

问题描述

当我使用来自 pyshark 的 LiveCapture 时,我想将 Python 中的十六进制输出转换为 ASCII。

我的代码

capture = pyshark.LiveCapture(interface='en1',bpf_filter='tcp port 5555 and len > 66',)

colored.OK("Interface bindée sur %s" % socket.gethostbyname(socket.gethostname()))

for packet in capture.sniff_continuously():
   if packet.ip.src == socket.gethostbyname(socket.gethostname()):
            colored.OK("Send packets")
   else:
            colored.OK("Receive packets")
            print(''.join(packet.data.data.split(":")))
            print("")

接收数据包的输出

66787874798582124495051

我想直接在 python 输出中将此输出转换为 ASCII 字符 可能吗?

谢谢

解决方法

是的,可以直接转换。

def convert_HEX_to_ASCII(h):
chars_in_reverse = []
while h != 0x0:
    chars_in_reverse.append(chr(h & 0xFF))
    h = h >> 8

chars_in_reverse.reverse()
return ''.join(chars_in_reverse)

print (convert_HEX_to_ASCII(0x6176656e67657273))
print (convert_HEX_to_ASCII(0x636f6e766572745f4845585f746f5f4153434949))

参考链接,在线将 HEX 转换为 ASCII。 https://www.rapidtables.com/convert/number/ascii-to-hex.html 您可以手动验证输出并确认结果。

类似的代码可用于: https://www.geeksforgeeks.org/convert-hexadecimal-value-string-ascii-value-string/