-4

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!

Community
  • 1
  • 1
Roman
  • 69
  • 4
  • 10

3 Answers3

1

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.

mauve
  • 1,976
  • 12
  • 18
0

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.

Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37
0
for(int i = 0; i < 8; i++)
    buffer[i] = rand();
beerboy
  • 1,304
  • 12
  • 12