The*_*ght 2 python type-conversion data-conversion python-3.x
我的命令输出类似于0x53 0x48 0x41 0x53 0x48 0x49. 现在我需要将它存储在一个十六进制值中,然后将其转换为 ASCII 作为SHASHI.
我试过的-
int("0x31",16)然后使用decode("ascii")但没有运气将其解码为 ASCII 。"0x31".decode("utf16")这会引发错误 AttributeError: 'str' object has no attribute 'decode'其他一些随机编码和解码的东西通过Google. 但仍然没有运气。
问题:- 我如何以十六进制形式存储值0x53 0x48 0x41 0x53 0x48 0x49并将其转换SHASHI为验证值。
注意:对 Python 不太友好,所以如果这是一个新手问题,请见谅。
该int("0x31", 16)部分是正确的:
>>> int("0x31",16)
49
Run Code Online (Sandbox Code Playgroud)
但是要将其转换为字符,您应该使用该chr(...)函数:
>>> chr(49)
'1'
Run Code Online (Sandbox Code Playgroud)
将它们放在一起(在第一个字母上):
>>> chr(int("0x53", 16))
'S'
Run Code Online (Sandbox Code Playgroud)
并处理整个列表:
>>> [chr(int(i, 16)) for i in "0x53 0x48 0x41 0x53 0x48 0x49".split()]
['S', 'H', 'A', 'S', 'H', 'I']
Run Code Online (Sandbox Code Playgroud)
最后把它变成一个字符串:
>>> hex_string = "0x53 0x48 0x41 0x53 0x48 0x49"
>>> ''.join(chr(int(i, 16)) for i in hex_string.split())
'SHASHI'
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助!