Hi all,
I've been struggling with this for an hour or so, I'm trying to take a string such as
'Hell' to '\x48\x65\x6c\x6c'
For what I'm doing, I require the \x before the ascii hex
This is a dated solution from StackOverflow, that doesn't work on Python3
>>> mystring = "Hello World"
>>> print ''.join(r'\x{02:x}'.format(ord(c)) for c in mystring)
\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64 My new solution goes like this:
mystring = b'hello world'
#convert to hex
mystring = hexlify(mystring)
mystring = mystring.decode('ascii')
# hex, like this 68656c6c6f20776f726c64
#add in the \x in the right spots
mystring = '\\x'.join(mystring[i:i + 2] for i in range(-2, len(mystring), 2))
#looks like this at this point \x68\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64
#I need it back into the "b" format, so I encode it
mystring=mystring.encode(ascii)
# This breaks everything, now it becomes:
# b'\\x68\\x65\\x6c\\x6c\\x6f\\x20\\x77\\x6f\\x72\\x6c\\x64'
# I specifically can't use the double backslashes.Any ideas how to fix this or am I going about this all wrong? Thanks
Decode Hex String in Python 3 - Stack Overflow
How to store Hex and convert Hex to ASCII in Python? - Stack Overflow
hex string to character in python - Stack Overflow
From hex to ascii in python - Stack Overflow
Something like:
>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'
Just put the actual encoding you are using.
import codecs
decode_hex = codecs.getdecoder("hex_codec")
# for an array
msgs = [decode_hex(msg)[0] for msg in msgs]
# for a string
string = decode_hex(string)[0]
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!
>>> import binascii
>>> s = b'SHASHI'
>>> myWord = binascii.b2a_hex(s)
>>> myWord
b'534841534849'
>>> binascii.a2b_hex(myWord)
b'SHASHI'
>>> bytearray.fromhex("534841534849").decode()
'SHASHI'
In Python2
>>> "437c2123".decode('hex')
'C|!#'
In Python3 (also works in Python2, for <2.6 you can't have the b prefixing the string)
>>> import binascii
>>> binascii.unhexlify(b"437c2123")
b'C|!#'
In [17]: data = "437c2123"
In [18]: ''.join(chr(int(data[i:i+2], 16)) for i in range(0, len(data), 2))
Out[18]: 'C|!#'
Here:
for i in range(0, len(data), 2)iterates over every second position indata:0,2,4etc.data[i:i+2]looks at every pair of hex digits'43','7c', etc.chr(int(..., 16))converts the pair of hex digits into the corresponding character.''.join(...)merges the characters into a single string.