Cryptographically random numbers

Paul Rubin http
Tue Mar 7 06:03:55 CET 2006

"Tuvas" <tuvas21 at> writes:
> Wait, I now see that there is a native base 2 log in python, so I will
> just do that rather than my adhoc way. The reason for adding one is to
> make sure there isn't any problems if the log is, for instance, 2.2. It
> will always round up. It's better to have to try twice to make sure the
> number can have the max range than never use the top half, as the first
> version did... That changes the function to:

OK, if the log is one too high, you just have to do a few additional

> As to the s2num(text), well, that looks really neat. Is there an easy
> way to do the reverse of that? Thanks!

from binascii import unhexlify
def num2s(n):
  s = '%X' % n
  if len(s) % 2 == 1:
    s = '0' + s                 # make sure length of hex string is even
  return unhexlify(s)

More information about the Python-list mailing list