Alex Rivera | Logout

quickest way to generate random bits

Asked 2009-05-15T08:41:18.983
13

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.

Edit
Report

2 Answers

4

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

answered 2009-05-15T08:48:43.893
3

As you say just generate random integers.
Then you have 32 random bits with ones and zeroes all equally probable.

Get the bits in a loop:

for (int i = 0; i < 32; i++)
{
  randomBit = (randomNum >> i) & 1
  ...
  // Do your thing
}

Repeat this for as many times you need to to get the correct amount of bits.

answered 2009-05-15T08:49:05.453

Your Answer