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)
'\x17\x96e\x94]\xa0\xb8\x1e\x8b\xee\xdd\xe9\x91^\x9c\xda\x94\t\xe8S\xa1Oe_'
>>> os.urandom(24).encode('hex')
'cd48e1c22de0961d5d1bfb14f8a66e006cfb1cfbf3f0c0f3'
>>> int(os.urandom(24).encode('hex'), 16)
625318378251135334886162535673249000280269152689162062986L
>>> bin(int(os.urandom(24).encode('hex'), 16))
'0b10100010101001110001101011101111010000111101010010110011111101111101111010100111100000001010100100001000100101010011100001001100011000011000000101101111100001011111011101001110011010001000010'

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

>>> import os
>>> os.urandom(24)
b':\xea\x8b\xb8\xf4\x04q\xc9$\xd9B\xdf\xaf\xcer\xa0t`Q:\xab{&\xfc'
>>> os.urandom(24).hex()
'11fe838db0c5f661b09f2f7a8de5ac44395e2fdc8128d211'
>>> int(os.urandom(24).hex(), 16)
1970467794856825403422320664826041246218521986958597162907
>>> bin(int(os.urandom(24).hex(), 16))
'0b111101001000010010001110011110010001101100000010011000000001111001101111011111010111110111011110110110110001111010100100000110110111101011000100011010001111001110111001110001010101011001001001'
Advertisements
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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: