How to generate a random int in C?

后端 未结 27 2090
故里飘歌
故里飘歌 2020-11-22 00:31

Is there a function to generate a random int number in C? Or will I have to use a third party library?

27条回答
  •  情歌与酒
    2020-11-22 00:37

    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:

    • Use libsodium's randombytes API
    • Re-implement what you need from libsodium's sysrandom implementation yourself, very carefully
    • More broadly, use /dev/urandom, not /dev/random. Not OpenSSL (or other userspace PRNGs).

    For example:

    #include "sodium.h"
    
    int foo()
    {
        char myString[32];
        uint32_t myInt;
    
        if (sodium_init() < 0) {
            /* panic! the library couldn't be initialized, it is not safe to use */
            return 1; 
        }
    
    
        /* myString will be an array of 32 random bytes, not null-terminated */        
        randombytes_buf(myString, 32);
    
        /* myInt will be a random number between 0 and 9 */
        myInt = randombytes_uniform(10);
    }
    

    randombytes_uniform() is cryptographically secure and unbiased.

提交回复
热议问题