How to store Hex and convert Hex to ASCII in Python?

梦想与她 提交于 2020-05-30 09:57:26

问题


My Command output is something like 0x53 0x48 0x41 0x53 0x48 0x49. Now i need to store this in a hex value and then convert it to ASCII as SHASHI.

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.
  2. "0x31".decode("utf16")this throws an error AttributeError: 'str' object has no attribute 'decode'

Some other stuffs with random encoding and decoding whatever found through 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.

Note: Not so friendly with Python, so please excuse if this is a novice question.


回答1:


The int("0x31", 16) part is correct:

>>> int("0x31",16)
49

But to convert that to a character, you should use the chr(...) function instead:

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




回答2:


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():

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




回答3:


>>> import binascii
>>> s = b'SHASHI'
>>> myWord = binascii.b2a_hex(s)
>>> myWord
b'534841534849'
>>> binascii.a2b_hex(myWord)
b'SHASHI'


>>> bytearray.fromhex("534841534849").decode()
'SHASHI'


来源:https://stackoverflow.com/questions/49400780/how-to-store-hex-and-convert-hex-to-ascii-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!