python编码十六进制填充每个字符00 [英] python encode hex pad every character with 00

查看:371
本文介绍了python编码十六进制填充每个字符00的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用00填充每个字符,以获取要转换为十六进制的字符串.有什么办法可以在python 2.5.2中做到这一点?

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?

例如

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

当前正在打印

483a5c6d7966696c65706174682e6d7966696c65656e64696e67

但是它应该打印

48003a005c00 etc.

此外,我希望所有字符都大写-有什么方法可以做到这一点?

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

我还想知道为什么十六进制有时会用这种方式填充00s吗?

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

推荐答案

最简单的方法是

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

但是您确定要此输出而不是UTF-16编码的字符串吗?

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'

这篇关于python编码十六进制填充每个字符00的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆