2

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?

1
  • 2
    Just generate 32-bit random numbers and convert them to binary strings... Commented Dec 25, 2021 at 3:52

4 Answers 4

3
import random

rnd_32bit = f'{random.getrandbits(32):=032b}'
Sign up to request clarification or add additional context in comments.

1 Comment

Simple and pythonic.
0

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

Comments

0

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

6 Comments

Why would you get 32 bytes in order to get 32 bits?
Change nbytes=4 and you might be onto something, however you still need to do the crux of the question, convert it to a binary string.
I misread that part, thanks. I'll update!
Closer, however I don't think bin outputs 32-bits, it may need to be padded with zeros to be 32 bits all the time...
|
0

You can use this function random_binary_length_n, which only needs two packages of random and math. This function can generate a random binary strings of length n (default is 32, but you can change it to another length you want):

import random, math
def random_binary_length_n(n=32):
    b_r = [] 
    r = random.randint(0, 2**n)
    lsts = [[0,1]]*n
    for j, J in enumerate(lsts):                          
        sizes = math.prod([len(l) for l in lsts][(j+1):]) 
        r_j = r//sizes % len(J) 
        b_r.append(J[r_j]) 
    b_s = ''.join(map(str, b_r))
    return b_s

Input:

random_binary_length_n(32)

Output:
'11010011000000001101111100110001'

Input:

random_binary_length_n(4)

Output:
'1011'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.