有没有办法填充到偶数位?
我正在尝试创建一些需要传输的数据的十六进制表示(具体来说,采用 ASN.1 表示法)。在某些时候,我需要将数据转换为其十六进制表示形式。由于数据以字节序列的形式传输,因此如果长度为奇数,则必须用 0 填充十六进制表示形式。
示例:
>>> hex2(3)
'03'
>>> hex2(45)
'2d'
>>> hex2(678)
'02a6'
目标是为 hex2
找到一个简单、优雅的实现。
目前我使用hex
,去掉前两个字符,然后用0
填充字符串(如果它的长度是奇数)。不过,我想找到一个更好的解决方案,以供以后参考。我查看了 str.format
,但没有找到任何可以填充到倍数的内容。
I'm trying to create a hex representation of some data that needs to be transmitted (specifically, in ASN.1 notation). At some points, I need to convert data to its hex representation. Since the data is transmitted as a byte sequence, the hex representation has to be padded with a 0 if the length is odd.
Example:
>>> hex2(3)
'03'
>>> hex2(45)
'2d'
>>> hex2(678)
'02a6'
The goal is to find a simple, elegant implementation for hex2
.
Currently I'm using hex
, stripping out the first two characters, then padding the string with a 0
if its length is odd. However, I'd like to find a better solution for future reference. I've looked in str.format
without finding anything that pads to a multiple.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
老实说,我不确定问题是什么。您所描述的内容的简单实现如下:
我不一定称其为“优雅”,但我肯定会称其为“简单”。
To be totally honest, I am not sure what the issue is. A straightforward implementation of what you describe goes like this:
I would not necessarily call this "elegant" but I would certainly call it "simple."
Python 的
binascii
模块的b2a_hex
保证返回偶数长度的字符串。技巧是将整数转换为字节串。 Python3.2 及更高版本内置了 int:
Python's
binascii
module'sb2a_hex
is guaranteed to return an even-length string.the trick then is to convert the integer into a bytestring. Python3.2 and higher has that built-in to int:
可能想看看 struct 模块,它是为面向字节的 i/o 设计的。
Might want to look at the struct module, which is designed for byte-oriented i/o.