python encode hex pad every character with 00

久未见 提交于 2019-12-11 11:54:51

问题


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?


回答1:


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'


来源:https://stackoverflow.com/questions/36245327/python-encode-hex-pad-every-character-with-00

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!