Possible Duplicate:
Random long long generator C++
Random long long using boost
I have an 8 bytes long buffer, i need to fill it pseudo-random bytes, how can i do it using C++ and maybe boost.
Thanks!
Possible Duplicate:
Random long long generator C++
Random long long using boost
I have an 8 bytes long buffer, i need to fill it pseudo-random bytes, how can i do it using C++ and maybe boost.
Thanks!
Try this:
#include <iostream>
#include <boost/random/random_device.hpp>
#include <boost/cstdint.hpp>
int main (int argc, char* argv[])
{
boost::uint32_t buffer[2]; // 8 bytes
boost::random::random_device rng;
// generate wants 32-bit integers to fill which is why
// we use boost::uint32_t here instead of char buffer[8] for example.
rng.generate(buffer, buffer + 2);
for (int i = 0; i < 2; ++i)
std::cout << (int) buffer[i] << std::endl;
return 0;
}
I have not compile-tested this but from the reading the reference I gather it ought to be correct.
For boost, check out http://www.boost.org/doc/libs/1_52_0/doc/html/boost_random.html (coincidentally, the first google result when searching for "boost random").
If you can compile using C++11, you could see if std::random_device will work. Check out http://www.cplusplus.com/reference/random/random_device/ for more details on that.
If neither of those will work, and you are sure you just want pseudo-random bytes and don't have specific security requirements: Grab some information from the machine you're running on that is not static (e.g. the current time, the process ID and a monotonically-increasing counter) stuff them all in a string (getting something like "1354654195-4710-1" as a result) and MD5 (or SHA-1) the contents of the string. You will get back 16 (or 20) bytes. Pick 8 of those, and stuff them in your buffer. Tada.
You should not use these techniques if you need this random buffer for cryptographic purposes.