Reputation: 391
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.
Upvotes: 9
Views: 3787
Reputation: 38462
Python's binascii
module's b2a_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:
from binascii import b2a_hex
def hex2(integer):
return b2a_hex(integer.to_bytes((integer.bit_length() + 7) // 8, 'big'))
Upvotes: 0
Reputation: 500495
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."
Upvotes: 7
Reputation: 798814
def hex2(n):
x = '%x' % (n,)
return ('0' * (len(x) % 2)) + x
Upvotes: 8
Reputation: 13121
Might want to look at the struct module, which is designed for byte-oriented 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'
Upvotes: -1