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?

AndW
  • 726
  • 6
  • 31

3 Answers3

3
import random

rnd_32bit = f'{random.getrandbits(32):=032b}'
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
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).

Fish
  • 459
  • 2
  • 6
  • 1
    Why would you get 32 *bytes* in order to get 32 *bits*? – Mark Ransom Dec 25 '21 at 04:00
  • 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*. – Ron Beyer Dec 25 '21 at 04:01
  • I misread that part, thanks. I'll update! – Fish Dec 25 '21 at 04:02
  • 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... – Ron Beyer Dec 25 '21 at 04:10
  • @RonBeyer that's easy to fix: [Converting from hex to binary without losing leading 0's python](https://stackoverflow.com/q/3258330/5987). – Mark Ransom Dec 25 '21 at 04:18
  • @MarkRansom Of course it is... but it should be in this answer (or linked in the answer). I think it's fixed now, but I didn't DV. – Ron Beyer Dec 25 '21 at 04:19
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"))
Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26