pick4pony
pick4pony

Reputation: 63

how to create a random bit64 value

I am having trouble trying to generate a random unsigned __int64 value, does anyone have a quick and effective way of doing something like this? below is what i am doing, check the code below.

unsigned __int64 m_RandomKey = 0;

while(m_RandomKey == 0)
{
    m_RandomKey = (unsigned __int64) rand() << 32 | rand();
}

What is the best way to generate a unsigned __int64 key so that is is hard to get the same key again after a while or even at all? it doesn't have to be unique as long as there remains a 1 in 18,446,744,073,709,551,615 chance of it not doing it again!

Upvotes: 4

Views: 1430

Answers (2)

Elemental
Elemental

Reputation: 7466

I think your method is fast, portable and good enough. As long as you initialise the random seed well this should work very well. Rand() may not be a perfect uniform distribution but it is pretty close.

As @Pete mentions below the Rand() is only sure to work across a 16 bit number so a slightly more complex expression might be better for true portability: m_RandomKey = (unsigned __int64)( (rand() << 48) | (rand() << 32)| (rand() << 16)|rand());

Still fast and definitely better.

Upvotes: 0

SirDarius
SirDarius

Reputation: 42879

If you are using C++11, you can use std::mt19937_64, a native 64 bits implementation of the Mersenne twister algorithm.

See http://en.cppreference.com/w/cpp/numeric/random.

It is available in Visual C++ 2010 and 2012 (http://msdn.microsoft.com/en-us/library/ee462314(v=vs.100).aspx).

Upvotes: 7

Related Questions