Ahmed Sabti
Ahmed Sabti

Reputation: 27

rand() Function to give a 32-bit random unsigned int

I have some trouble coding a Function that takes 3 rand()- values and generates a 32-bit value. Specifically it has to be 15-bit from the first rand() operation; then attaching another 15-bit from the second rand() operation; and lastly attaching 2-bits from the last rand() operation;

My idea was something like this

unsigned int x = (rand()<<17 | rand()<<2 ) | rand()>>13;

However i don´t think this function gives me values of the entire unsigned int range, my guess it has something to do with the fact that rand() gives you at least a value of 32767 (as far as i understand).

I hope someone can help me out.

Cheers

Upvotes: 0

Views: 1425

Answers (1)

There are two problems with your code. First of all rand returns int and not unsigned int, and if your unsigned int is 32 bits, then bit shift left to position 17 is invalid if top bit is set. The second problem is that if rand indeed does return more than 15 bits then you're getting too many. One simple fix for both of these would be to & with 0x7fffu - that would ensure only 15 bits are set and that the resulting value is unsigned:

unsigned int x = ((rand() & 0x7fffu)<<17 | (rand() & 0x7fffu)<<2 ) | (rand() & 0x7fffu)>>13;

Another one, if you know the values are truly independent (Edit: and as Eric noticed, also a power of two), would be to use xor ^ instead of or - this would ensure that all values are still possible.


Note though that any random number generator that returns values only from 0 to 32767 is a suspect for being really bad and it is very likely that the lower-order bits are not very independent and it can be that you will end up not being able to generate all values nevertheless...

Upvotes: 1

Related Questions