How to create a random bit64 value

I'm having trouble creating a random unsigned __int64 value, does anyone have a quick and efficient way to do 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 create an unsigned __int64 key, so is it hard to get the same key again after a while or even at all? it should not be unique , as long as there is 1 in 18,446,744,073,709,551,615 chances that it will not do it again!

+4
source share
2 answers

If you use C ++ 11, you can use std::mt19937_64 , std::mt19937_64 's built-in 64-bit implementation of the Twers 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 ).

+7
source

I think your method is fast, portable and good enough. While you initialize random seeds, this should work very well. Rand () may not be a perfect uniform distribution, but it is pretty close.

As @Pete points out below, Rand () only works with 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.

0
source

Source: https://habr.com/ru/post/1479424/


All Articles