Search code examples
pythonhexpaddingencode

python encode hex pad every character with 00


I need to pad every character with 00 for a string that I am converting to hex. Is there any way to do this in python 2.5.2?

e.g.

hextext = "H:\myfilepath.myfileending"
encodedhex = str(hextext.encode('hex'))
print encodedhex

It currently prints

483a5c6d7966696c65706174682e6d7966696c65656e64696e67

But it should print

48003a005c00 etc.

Also, I was hoping for all characters to be upper case - is there any way to do this?

Im also wondering why does hex sometimes get padded with 00s in this way?


Solution

  • The simplest way would be

    >>> hextext = "H:\myfilepath.myfileending"
    >>> encodedhex = "".join(c.encode("hex")+"00" for c in hextext)
    >>> encodedhex
    '48003a005c006d007900660069006c00650070006100740068002e006d007900660069006c00650065006e00640069006e006700'
    >>> encodedhex.upper()
    '48003A005C006D007900660069006C00650070006100740068002E006D007900660069006C00650065006E00640069006E006700'
    

    But are you sure you want this output and not a UTF-16-encoded string?

    >>> hextext.encode("utf-16-le")
    'H\x00:\x00\\\x00m\x00y\x00f\x00i\x00l\x00e\x00p\x00a\x00t\x00h\x00.\x00m\x00y\x00f\x00i\x00l\x00e\x00e\x00n\x00d\x00i\x00n\x00g\x00'