Home >Backend Development >C++ >How Can I Generate Thoroughly Random Seeds for mt19937 in C ?
Problem:
Recent answers often suggest using
Portable and Thorough Seeding:
A portable and thorough approach to seeding mt19937 involves using a CSPRNG, such as:
Code Example:
#include <cstdint> #include <cstdlib> #include <fstream> size_t sysrandom(void* dst, size_t dstlen); std::uint_least32_t seed; sysrandom(&seed, sizeof(seed)); std::mt19937 gen(seed);
Linux Specialization with getrandom:
#if defined(HAVE_GETRANDOM) size_t sysrandom(void* dst, size_t dstlen) { int bytes = syscall(SYS_getrandom, dst, dstlen, 0); if (bytes != dstlen) { throw std::runtime_error("Unable to read N bytes from CSPRNG."); } return dstlen; } #endif
OpenBSD Special Case:
#if defined(HAVE_GETENTROPY) size_t sysrandom(void* dst, size_t dstlen) { int bytes = getentropy(dst, dstlen); if (bytes != dstlen) { throw std::runtime_error("Unable to read N bytes from CSPRNG."); } return dstlen; } #endif
Other Thoughts:
The above is the detailed content of How Can I Generate Thoroughly Random Seeds for mt19937 in C ?. For more information, please follow other related articles on the PHP Chinese website!