简体   繁体   中英

How to generate random 32bit integers in c++

My understanding is that RAND_MAX is dependent on the architecture of the machine. If the machine is 32bit, than rand() will only generate something up to 4byte. How do I generate a 32bit random integer on a 64bit machine with rand()?

Also, do I always need srand() if I want to generate billions of random integers with rand() later?

Using rand() with bit-hacking is seriously discouraged as it may lead to randomness issues in many cases.

The c++11 <random> header defines all the tools necessary for generating any kind of good quality random numbers, including integer of any length, floating point, etc...

I suggest watching this : https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

Since you are using rand() already, you probably don't have to worry about the period, so you can just mask the upper bits.

In general, you should do something like srand(time(NULL)) once at the top of your program. Otherwise, you will generate the same sequence of the billion random numbers every time you run the program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM