问题
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-
- I tried to store the values in hex as
int("0x31",16)
then decode this to ASCII usingdecode("ascii")
but no luck. "0x31".decode("utf16")
this throws an errorAttributeError: '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