[英]How to store Hex and convert Hex to ASCII in Python?
My Command output is something like 0x53 0x48 0x41 0x53 0x48 0x49
. 我的命令输出类似于
0x53 0x48 0x41 0x53 0x48 0x49
。 Now i need to store this in a hex value and then convert it to ASCII as SHASHI
. 现在,我需要将其存储为十六进制值,然后将其以
SHASHI
格式转换为ASCII。
What i tried- 我试过的
int("0x31",16)
then decode this to ASCII using decode("ascii")
but no luck. int("0x31",16)
然后使用decode("ascii")
将其解码为ASCII,但是没有运气。 "0x31".decode("utf16")
this throws an error AttributeError: 'str' object has no attribute 'decode'
"0x31".decode("utf16")
引发错误AttributeError: 'str' object has no attribute 'decode'
Some other stuffs with random encoding and decoding whatever found through Google
. 其他一些可以随机编码和解码的东西,可以通过
Google
找到。 But still no luck. 但是仍然没有运气。
Question :- How can i store a value in Hex like 0x53 0x48 0x41 0x53 0x48 0x49
and convert it's value as SHASHI
for verification. 问题:-我如何将十六进制值存储为
0x53 0x48 0x41 0x53 0x48 0x49
并将其值转换为SHASHI
以进行验证。
Note: Not so friendly with Python, so please excuse if this is a novice question. 注意:对Python不太友好,因此如果这是一个新手问题,请原谅。
The int("0x31", 16)
part is correct: int("0x31", 16)
部分正确:
>>> int("0x31",16)
49
But to convert that to a character, you should use the chr(...)
function instead: 但是要将其转换为字符,应改用
chr(...)
函数 :
>>> chr(49)
'1'
Putting both of them together (on the first letter): 将它们放在一起(在第一个字母上):
>>> chr(int("0x53", 16))
'S'
And processing the whole list: 并处理整个列表:
>>> [chr(int(i, 16)) for i in "0x53 0x48 0x41 0x53 0x48 0x49".split()]
['S', 'H', 'A', 'S', 'H', 'I']
And finally turning it into a string: 最后将其转换为字符串:
>>> hex_string = "0x53 0x48 0x41 0x53 0x48 0x49"
>>> ''.join(chr(int(i, 16)) for i in hex_string.split())
'SHASHI'
I hope this helps! 我希望这有帮助!
>>> import binascii
>>> s = b'SHASHI'
>>> myWord = binascii.b2a_hex(s)
>>> myWord
b'534841534849'
>>> binascii.a2b_hex(myWord)
b'SHASHI'
>>> bytearray.fromhex("534841534849").decode()
'SHASHI'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.