My requirement is to generate random bytes of data (not random numbers) aka uniformly distributed bits.
As such I was wondering what are the correct/efficient ways of doing this using C++11/14 random facilities. I've had a look around at the examples, but they all seem to focus on number generation (ints, floats etc)
Current solution I'm using is the following:
#include <vector>
#include <random>
int main()
{
std::random_device rd;
std::uniform_int_distribution<int> dist(0,255);
std::vector<char> data(1000);
for (char& d : data)
{
d = static_cast<char>(dist(rd) & 0xFF);
}
return 0;
}
What you're looking for is the std::independent_bits_engine
adaptor:
#include <vector>
#include <random>
#include <climits>
#include <algorithm>
#include <functional>
using random_bytes_engine = std::independent_bits_engine<
std::default_random_engine, CHAR_BIT, unsigned char>;
int main()
{
random_bytes_engine rbe;
std::vector<unsigned char> data(1000);
std::generate(begin(data), end(data), std::ref(rbe));
}
Note that the accepted answer is not strictly correct in a general case – random engines produce unsigned values belonging to a range [min()
, max()
], which doesn't necessarily cover all possible values of the result type (for instance, std::minstd_rand0::min() == 1
) and thus you may get random bytes that are not uniformly distributed if using an engine directly. However, for std::random_device
the range is [std::numeric_limits<result_type>::min()
, std::numeric_limits<result_type>::max()
], so this particular engine would also work well without the adaptor.