AndW
AndW

Reputation: 846

Generate random binary strings of length 32

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?

Upvotes: 2

Views: 2421

Answers (3)

Fish
Fish

Reputation: 455

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).

Upvotes: 0

Iain Shelvington
Iain Shelvington

Reputation: 32274

import random

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

Upvotes: 3

Yevhenii Kosmak
Yevhenii Kosmak

Reputation: 3860

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"))

Upvotes: 0

Related Questions