Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

quickest way to generate random bits

Tags:

c++

random

What would be the fastest way to generate a large number of (pseudo-)random bits. Each bit must be independent and be zero or one with equal probability. I could obviously do some variation on

randbit=rand()%2;

but I feel like there should be a faster way, generating several random bits from each call to the random number generator. Ideally I'd like to get an int or a char where each bit is random and independent, but other solutions are also possible.

The application is not cryptographic in nature so strong randomness isn't a major factor, whereas speed and getting the correct distribution is important.

like image 404
dagw Avatar asked May 15 '09 08:05

dagw


People also ask

How are random bits generated?

Random bits are generated by running a deterministic random bit generator (DRBG) on the entropy pool data bits. This algorithm is deterministic (it always produces the same output given the same input). The trick is to ensure that the DRBG is never fed the same value input twice!

What is a bit generator?

Definition. A random bit generator is a system whose output consists of fully unpredictable (i.e., statistically independent and unbiased) bits. In security applications, the unpredictability of the output implies that the generator must be also not observable and not manipulable by any attacker.

How do you make a bit?

Generating individual bits is the same as generating bit groups of length one. In every iteration, it creates an empty array groupBits = [] that will store the randomly generated bits. If the group length is one, then single bits will be generated. Otherwise, groups of multiple bits will be generated.


2 Answers

convert a random number into binary
Why not get just one number (of appropriate size to get enough bits you need) and then convert it to binary. You'll actually get bits from a random number which means they are random as well.

Zeros and ones also have the probability of 50%, since taking all numbers between 0 and some 2^n limit and counting the number of zeros and ones are equal > meaning that probability of zeros and ones is the same.

regarding speed
this would probably be very fast, since getting just one random number compared to number of bits in it is faster. it purely depends on your binary conversion now.

like image 76
Robert Koritnik Avatar answered Oct 08 '22 04:10

Robert Koritnik


Take a look at Boost.Random, especially boost::uniform_int<>.

like image 33
avakar Avatar answered Oct 08 '22 03:10

avakar