Generating random unsigned char values in C++

Ali picture Ali · Apr 4, 2012 · Viewed 13.9k times · Source

I was wondering how to generate random unsigned char values. My idea;
rand()%255; since unsigned chars support between 0-255. I was wondering if this method could be improved(or is it the most legit way to do this)

Answer

bames53 picture bames53 · Apr 4, 2012

The C++11 random number library is the best way if you want to stick to the standard library:

#include <random>

#include <functional>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <climits>

int main() {
    std::random_device r;
    std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};

    auto rand = std::bind(std::uniform_int_distribution<>(0, UCHAR_MAX),
                          std::mt19937(seed));

    std::generate_n(std::ostream_iterator<int>(std::cout," "), 25, rand);
}

The library provides some uniform random number engines and adapters to use with them to produce various distributions. Here we use a mt19937 engine (seeded using random_device (as a source of non-deterministic data if possible), and seed_seq to combine enough random data into a form suitable for filling out mt19937's internal state. Then we adapt the mt19937 using a uniform_int_distribution. By default this distribution will produce numbers uniformly distributed across the range supported by its template parameter, in this case unsigned char. So the function object we create will produce values in the range [0 256). Its results are demonstrated by writing out 25 values to the standard output.

There are distributions for other uses such as producing a normal distribution, simulating coin flips, or picking items out of a set with arbitrary weights (e.g. picking one of 3 items where the first is picked 50% of the time, the second is picked 10% of the time, and the third, 40% of the time).

Other engines are provided for different quality and performance characteristics. For example if you need a cryptographic random number generator, random_device may provide it if your implementation offers such capability.


Some additional resources.