Is there a function to generate a random int number in C? Or will I have to use a third party library?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Despite all the people suggestion
rand()
here, you don't want to userand()
unless you have to! The random numbers thatrand()
produces are often very bad. To quote from the Linux man page:Regarding portability,
random()
is also defined by the POSIX standard for quite some time now.rand()
is older, it appeared already in the first POSIX.1 spec (IEEE Std 1003.1-1988), whereasrandom()
first appeared in POSIX.1-2001 (IEEE Std 1003.1-2001), yet the current POSIX standard is already POSIX.1-2008 (IEEE Std 1003.1-2008), which received an update just a year ago (IEEE Std 1003.1-2008, 2016 Edition). So I would considerrandom()
to be very portable.POSIX.1-2001 also introduced the
lrand48()
andmrand48()
functions, see here:And pretty good pseudo random source is the
arc4random()
function that is available on many systems. Not part of any official standard, appeared in BSD around 1997 but you can find it on systems like Linux and macOS/iOS.My minimalistic solution should work for random numbers in range
[min, max)
. Usesrand(time(NULL))
before invoking the function.If you need secure random characters or integers:
As addressed in how to safely generate random numbers in various programming languages, you'll want to do one of the following:
randombytes
API/dev/urandom
, not/dev/random
. Not OpenSSL (or other userspace PRNGs).For example:
randombytes_uniform()
is cryptographically secure and unbiased.Edit: On Linux, you might prefer to use random and srandom.
Try this, I put it together from some of the concepts already referenced above: