Python String To Escaped Hex
Solution 1:
The string '1234'
is already equivalent to '\x31\x32\x33\x34'
:
>>> '\x31\x32\x33\x34''1234'>>> '\x31\x32\x33\x34' == '1234'True
thus encoding that to hex then decoding it again is.. busy work:
>>> '1234'.encode('hex').decode('hex')
'1234'
\xhh
is just a notation to help you create the values; when echoing a byte string Python will always display printable ASCII characters directly rather than use the \xhh
notation.
Hex notation here is just a way to express the values of each byte, which is really an integer between 0 and 255. Each byte in a Python string is then a byte with such a constrained value, and encoding to the 'hex'
codec produces a string with hex digits for those bytes, and bytes again from the hex digits.
As such, all you have to do is add the \x00
null bytes and the length:
MAGICSTRING = '1234'value = '\x00{}\x00{}'.format(MAGICSTRING, chr(len(MAGICSTRING) + 2))
Here the \xhh
notation is used to produce the null bytes, and the chr()
function produces the length 'byte'.
Demo:
>>>MAGICSTRING = '1234'>>>'\x00{}\x00{}'.format(MAGICSTRING, chr(len(MAGICSTRING) + 2))
'\x001234\x00\x06'
>>>'\x00{}\x00{}'.format(MAGICSTRING, chr(len(MAGICSTRING) + 2)) == '\x00\x31\x32\x33\x34\x00\x06'
True
Post a Comment for "Python String To Escaped Hex"