简体   繁体   English

如何在Python中存储十六进制并将十六进制转换为ASCII?

[英]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- 我试过的

  1. I tried to store the values in hex as int("0x31",16) then decode this to ASCII using decode("ascii") but no luck. 我试图将值以十六进制形式存储为int("0x31",16)然后使用decode("ascii")将其解码为ASCII,但是没有运气。
  2. "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! 我希望这有帮助!

Suppose you have this input: 假设您有以下输入:

s = '0x53 0x48 0x41 0x53 0x48 0x49'

You can store values in list like follow: 您可以存储在列表中,如下所示:

l = list(map(lambda x: int(x, 16), s.split()))

To convert it to ASCII use chr() : 要将其转换为ASCII,请使用chr()

res = ''.join(map(chr, l))

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM