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 w
What you're looking for is the std::independent_bits_engine adaptor:
#include
#include
#include
#include
#include
using random_bytes_engine = std::independent_bits_engine<
std::default_random_engine, CHAR_BIT, unsigned char>;
int main()
{
random_bytes_engine rbe;
std::vector 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
, std::numeric_limits
], so this particular engine would also work well without the adaptor.