generating a random number within range 0 to n where n can be > RAND_MAX

前端 未结 9 2068
梦毁少年i
梦毁少年i 2021-01-18 08:32

How can I generate a random number within range 0 to n where n can be > RAND_MAX in c,c++?

Thanks.

9条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-18 09:01

    suppose you want to generate a 64-bit random number, you could do this:

    uint64_t n = 0;
    for(int i = 0; i < 8; ++i) {
        uint64_t x = generate_8bit_random_num();
        n = (n << (8 * i)) | x;
    }
    

    Of course you could do it 16/32 bits at a time too, but this illustrates the concept.

    How you generate that 8/16/32-bit random numbers is up to you. It could be as simple as rand() & 0xff or something better depending on how much you care about the randomness.

提交回复
热议问题