Is the difference between RAND_MAX and UINT_MAX different?

My homework involves creating random integers between 0and 2^30. In the past, we have learned that it rand()only returns integers up RAND_MAX, which is less UINT_MAX, and we can use bit offsets to fill this capacity UINT_MAX. From some of the readings I made (here on SO), I understand that this may not be a good idea if the distribution of these numbers matters to me. Having said that, my professor pointed out this method.

My question is, how much is the bit shifted? Will there be a difference between RAND_MAXand UINT_MAXsuch that there exists a safe constant with which the bit was shifted? Or is there some kind of initial research that needs to be done to determine the number by which the bit can be shifted? Should I just shift the bit a bit and check on UINT_MAX?

I ask that UINT_MAXat least a certain number ( 65535) is defined , but on my machine a UINT_MAXlot more ( 4294967295). I was worried that I could finish my homework on the weekend, come to school and find everything that didn't work well enough to comply.

Thank!

Literature:

I read a couple of similar questions, but could not get an answer from them.

Is value RAND_MAXalways (2^n)-1?

0 n, n > RAND_MAX

, , , ?

+5
2

, RAND_MAX UINT_MAX . , UINT_MAX RAND_MAX 2^k - 1. UINT_MAX . sizeof(int)=32 , k=32, sizeof(int)=64 bit, k=64 .. RAND_MAX. , RAND_MAX 2^k - 1. ? , rand().

(.. C x(k), rand(), x(k+1))

  • , (a, c m) . , .. , m UINT_MAX, . , , , m , UINT_MAX. m .

  • , , rand() , , . mod foo % (2^k - 1), foo & (1<<k-1). k Mersenne prime.

, k=31, 2^31-1 = 2147483647. 32- , UINT_MAX=2^32-1 = 4294967295. 64- UINT_MAX=2^64-1=18446744073709551615, RAND_MAX 2^61-1 = 2305843009213693951.

, : , , . , init. ++, static_assert , , . Boost , ++ 11... .. ( is_power_of_two_minus_one ):

unsigned int myrand()
{
        static_assert(sizeof(int)==4,"sizeof(unsigned int) != 4");
        static_assert(is_power_of_two_minus_one(RAND_MAX),"RAND_MAX not a power of two minus one");
        static_assert(is_power_of_two_minus_one(UINT_MAX),"UINT_MAX not power of two minus one");
        unsigned int raw_rand=rand();
        // do your bit shift to adjust raw_rand
        return raw_rand;
}
+5

, , , ?

, . , .

RAND_MAX 2^n - 1, . , , , , max 2^n - 1, , .

, , . , .

ssh , ( ) ?

+3

All Articles