Python String to Escaped Hex

后端 未结 1 1471
别那么骄傲
别那么骄傲 2021-01-14 13:15

I have some python code below I managed to cobble together to achieve what I needed, but being quite new to python I believe there should be a much more elegant solution tha

相关标签:
1条回答
  • 2021-01-14 13:44

    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
    
    0 讨论(0)
提交回复
热议问题