Integers to octet strings (I2OSP)

Paul Rubin http
Wed Jul 14 01:34:15 CEST 2004

Tim Churches <tchur at> writes:
> What is the most efficient method in Python for converting positive
> integers (including long integers) to octet strings, as per the common
> cryptographic data conversion conversion I2OSP (formal definition can be
> found here: )? I thought of converting
> the integer to hex with hex() and then converting pairs of the resulting
> hex characters into bytes using int() and then chr(), but this seems a
> bit clunky.

It's ugly but it's quite efficient.  Here's how I do it:

from binascii import hexlify as hexl, unhexlify as unhexl

# convert numbers to binary strings, and back.  The incoming numbers
# can be ints, longs, or mpz's.  Their hex representations all look
# different from each other so we have to account for that.
def nstr(n):
    h=hex(n)[2:]                        # remove 0x prefix
    if h[-1:]=='L': h=h[:-1]            # remove L suffix if present
    if len(h)&1: h="0"+h
    return unhexl(h)

def strn(s):
    return long(hexl(s),16)

More information about the Python-list mailing list