Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 279
TheMightyNight Avatar asked Dec 11 '25 08:12

TheMightyNight


2 Answers

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!

like image 72
filbranden Avatar answered Dec 13 '25 20:12

filbranden


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


>>> bytearray.fromhex("534841534849").decode()
'SHASHI'
like image 44
papu Avatar answered Dec 13 '25 20:12

papu