[英]Is there a way to pad to an even number of digits?
I'm trying to create a hex representation of some data that needs to be transmitted (specifically, in ASN.1 notation). 我正在尝试创建一些需要传输的数据的十六进制表示(具体来说,在ASN.1表示法中)。 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.
由于数据是作为字节序列传输的,如果长度为奇数,则必须用0填充十六进制表示。
Example: 例:
>>> hex2(3)
'03'
>>> hex2(45)
'2d'
>>> hex2(678)
'02a6'
The goal is to find a simple, elegant implementation for hex2
. 目标是为
hex2
找到一个简单,优雅的实现。
Currently I'm using hex
, stripping out the first two characters, then padding the string with a 0
if its length is odd. 目前我正在使用
hex
,剥离前两个字符,然后如果长度为奇数则用0
填充字符串。 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. 我已经查看了
str.format
而没有找到任何str.format
到多个的东西。
def hex2(n):
x = '%x' % (n,)
return ('0' * (len(x) % 2)) + x
To be totally honest, I am not sure what the issue is. 说实话,我不确定问题是什么。 A straightforward implementation of what you describe goes like this:
直接实现您描述的内容如下:
def hex2(v):
s = hex(v)[2:]
return s if len(s) % 2 == 0 else '0' + s
I would not necessarily call this "elegant" but I would certainly call it "simple." 我不一定称之为“优雅”,但我当然称之为“简单”。
Python's binascii
module's b2a_hex
is guaranteed to return an even-length string. Python的
binascii
模块的b2a_hex
保证返回一个偶数长度的字符串。
the trick then is to convert the integer into a bytestring. 然后,技巧是将整数转换为字节串。 Python3.2 and higher has that built-in to int:
Python3.2及更高版本具有内置到int:
from binascii import b2a_hex
def hex2(integer):
return b2a_hex(integer.to_bytes((integer.bit_length() + 7) // 8, 'big'))
Might want to look at the struct module, which is designed for byte-oriented i/o. 可能要查看struct模块,它是为面向字节的i / o而设计的。
import struct
>>> struct.pack('>i',678)
'\x00\x00\x02\xa6'
#Use h instead of i for shorts
>>> struct.pack('>h',1043)
'\x04\x13'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.