TheMightyNight
TheMightyNight

Reputation: 159

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.

Upvotes: 2

Views: 16288

Answers (4)

MariusMihai92
MariusMihai92

Reputation: 29

I don't know if this solution is OK for your problem but it's a nice way to convert HEX to ASCII. The code snippet is below:

# Your raw data, the hex input
raw_data = '0x4D6172697573206120636974697420637520707974686F6E21'

# Slice string to remove leading `0x`   
hex_string = raw_data[2:]

# Convert to bytes object.                                          
bytes_object = bytes.fromhex(hex_string) 

# Convert to ASCII representation.                          
ascii_string = bytes_object.decode("ASCII") 

# print the values for comparison
print("\nThe input data is: {} \nwhile the string is: {} \n".format(raw_data,ascii_string))

Upvotes: 0

papu
papu

Reputation: 415

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


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

Upvotes: 2

ailin
ailin

Reputation: 501

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

Upvotes: 1

filbranden
filbranden

Reputation: 8898

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!

Upvotes: 9

Related Questions