Home > python > Generate a 192-bit random number

Generate a 192-bit random number

import os
os.urandom(24)    # length: 24 bytes, i.e. 24*8=192 bits

See the doc. here.

Formatting its output:

>>> os.urandom(24)
>>> os.urandom(24).encode('hex')
>>> int(os.urandom(24).encode('hex'), 16)
>>> bin(int(os.urandom(24).encode('hex'), 16))

Update (20170523)
The code above is for Python 2. Here is the Python 3 version:

>>> import os
>>> os.urandom(24)
>>> os.urandom(24).hex()
>>> int(os.urandom(24).hex(), 16)
>>> bin(int(os.urandom(24).hex(), 16))
Categories: python Tags: ,
  1. May 22, 2017 at 22:34

    Is this MicroPython? On my MicroPython ESP8266 (an Adafruit Feather ESP8266 board),
    the os library module has no “encode” member function, but does have a “decode” member function. “as the keyword “encode” been replaced by “decode”? What I am trying to do is to re-make os.random into a function that will return a random int. Was not able to find a random library module with MicroPython, but I did come across os.urandom, but I am not sure how to make the various random byte patterns it returns into a function that returns a random int. Seems os.urandom interprets the number it gets back from the system and formats it several different formats which complicates it use by unsophisticated programmers like myself. Any assistance would be nice.

    • May 23, 2017 at 05:57

      I updated the post with a Python 3 solution. This is normal Python, I’ve never tried MicroPython.

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: