'Generate random 128 bit in c++ without boost
I have a datatype of size 128 bit, and I like to generate a random value without using boost or any third party headers/libraries. I wrote the below code snippet and it's working fine, but I want to know if there are any issues/pitfalls with the approach.
#include <stdlib.h>
#include <time.h>
#include <array>
#include <iostream>
#include <random>
int main() {
constexpr int size = 16;
std::array<std::uint8_t, size> randomID;
std::mt19937_64 gen_{std::random_device{}()};
std::uniform_int_distribution<std::uint8_t> dis_{1};
for (int i = 0; i < randomID.size(); i++) {
randomID[i] = dis_(gen_);
std::cout << unsigned(randomID[i]) << " ";
}
return 0;
}
Solution 1:[1]
One issue with the posted approach is that it will never generate a 0 octet.
std::uniform_int_distribution<std::uint8_t> dis_{1};
// ^ the range will be [1, 255]
You could also use a distribution of uint64_t and spread the bits in the array
std::uniform_int_distribution<std::uint64_t> dis_{};
for ( size_t i{}; i < randomID.size(); i += 8 )
{
auto r{ dis_(gen_) };
for ( unsigned j{}; j < 8; ++j )
{
randomID[i + j] = (r >> (j * 8)) & 0xFF;
std::cout << unsigned(randomID[i + j]) << " ";
}
}
Consider also using a std::seed_seq to initialize std::mt19937.
std::random_device rd{};
std::seed_seq ss{ rd(), rd(), rd() };
// ^^^^^^^^^^^^^^^^ Increase the entropy.
std::mt19937_64 gen_{ ss };
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
