Integers to octet strings (I2OSP)

"Martin v. Löwis" martin at
Wed Jul 14 00:44:09 CEST 2004

Tim Churches wrote:
> 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: )? 

For what value of l? For l in {1, 2, 4, 8}, the struct module is most
efficient. For larger values of l, you can repeatedly divide by 2**32.
For other values of l, you can round to the next support value, and
strip off the leading zeroes.

Of course, the specification in the RFC is flawed: In the resulting
byte string, X_0 is not used, and X_l is always 0. I doubt this is
intended :-)


More information about the Python-list mailing list