0

I need to test the randomness of a Blum Blum Shub generator I built in Python, using the ENT randomness tests. I have a python array of pseudo random bits of form [0, 1, 1, 1, 0, 0, 1, 0, 0, ...], and I need to write this sequence of bits into a binary file that I can then run through the ENT randomness test platform (ENT website linked here).

Would anyone be able to help me find a way to do this? I tried using the struct package, but I do not think I am using it correctly: if p is the bit array as shown above, I am writing to the file as follows using struct:

f=open("myfile","wb")
myfmt='b'*len(p)
bin=struct.pack(myfmt,*p)
f.write(bin)
f.close()

Could anyone point out how to correctly do this? Further, if instead the array was not of 0, 1 values but instead composed of the pseudo random positive integers, what would be the correct way to write these to a file to test for randomness?

user918212
  • 143
  • 4
  • What's the error you get? We don't have `p` so we can't check :( I see from https://docs.python.org/3/library/struct.html#format-characters that the 'b' format string for a byte, so whatever `p` is an array of (something between -128 and 127), it should dump them into a binary file, one byte per input. For example, the following emits a 3-byte file as expected: `with open('myfile', 'wb') as fid: fid.write(struct.pack('3b', *[1,0,1]))` – Ahmed Fasih Apr 12 '20 at 01:08
  • If you want random bits I suggest you use in integer and set the bits with bit operators. They are inherently packed, then. – Keith Apr 12 '20 at 01:10
  • @AhmedFasih `p` looks like the array `[0, 1, 1, 0, 1, 1, 0, 1, ...]`. It is not that I get an error but that I am not sure if this is correct. – user918212 Apr 12 '20 at 01:10
  • @Keith So it would be better to take the "raw" array of random integers and convert those to bits directly? I would happily close an answer that explained how to do this and why this was correct. – user918212 Apr 12 '20 at 01:12
  • Ok, then the output file will one one byte per bit. If your generator produces positive integers, you can use `H`, `I`, `L`, or `Q` format characters for 1, 2, 4, or 8-bytes per element in the output file respectively. I'm not familiar with ENT though, so it's possible this isn't the format it requires (i.e., it might want random bits packed with no padding). – Ahmed Fasih Apr 12 '20 at 01:14
  • Basically, you output a stream of bits (represented as integers), the but IO needs bytes. So you do something like a shift register to shift the bits into bytes and collect the bytes, then write the raw byte string out. – Keith Apr 12 '20 at 02:16
  • My answer to [How to read bits from a file?](https://stackoverflow.com/questions/10689748/how-to-read-bits-from-a-file) might help because it also shows how to write them. – martineau Apr 12 '20 at 02:30

0 Answers0