Home > Enterprise >  Generate random binary strings of length 32
Generate random binary strings of length 32

Time:12-25

I want to generate 500 random binary strings of length 32 (i.e., from 00000...0 to 1111...1 where each string is length 32). I'm wondering how I could do this efficiently or Pythonically.

Right now, I randomly choose between 0 and 1 32 times and then append the results into a string. This seems pretty inefficient and not pythonic. Is there some library functions i could use for this?

CodePudding user response:

import random

rnd_32bit = f'{random.getrandbits(32):=032b}'

CodePudding user response:

Since python 3.9 you can do it this way:

from random import randbytes

def rand_32bit_string(byte_count):
    return "{0:b}".format(int.from_bytes(randbytes(4), "big"))

CodePudding user response:

Easiest way is probably to use the secrets library (part of the python standard library as of python 3.6) and its token_bytes function.

import secrets

s = secrets.token_bytes(nbytes=4)

This question has various solutions for converting from bytes to a str of bit digits. You could do the following:

s = bin(int(secrets.token_hex(nbytes=4), 16))[2:].rjust(32, '0')

Throw this in a for loop and you're done!


In python 3.9 you also have the option of random.randbytes, e.g. random.randbytes(4), which behaves similarly (though secrets will use a cryptographically secure source of randomness, if that matters to you).

  • Related