Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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). 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.

like image 390
Nan L Avatar asked Dec 06 '10 16:12

Nan L


1 Answers

def hex2(n):
  x = '%x' % (n,)
  return ('0' * (len(x) % 2)) + x
like image 185
Ignacio Vazquez-Abrams Avatar answered Oct 25 '22 06:10

Ignacio Vazquez-Abrams