I'm hoping that somebody can give me an understanding of why the code works the way it does. I'm trying to wrap my head around things but am lost.
My professor has given us this code snippet which we have to use in order to generate random numbers in C. The snippet in question generates a 64-bit integer, and we have to adapt it to also generate 32-bit, 16-bit, and 8-bit integers. I'm completely lost on where to start, and I'm not necessarily asking for a solution, just on how the original snippet works, so that I can adapt it form there.
long long rand64()
{
int a, b;
long long r;
a = rand();
b = rand();
r = (long long)a;
r = (r << 31) | b;
return r;
}
Questions I have about this code are:
I'm making the relatively safe assumption that, in your computer's C implementation, long long
is a 64-bit data type.
The key here is that, since long long r
is signed, any value with the highest bit set will be negative. Therefore, the code shifts r
by 31 bits to avoid setting that bit.
The |
is a logical bit operator which combines the two values by setting all of the bits in r
which are set in b
.
EDIT:
After reading some of the comments, I realized that my answer needs correction. rand()
returns a value no more than RAND_MAX
which is typically 2^31-1. Therefore, r
is a 31-bit integer. If you shifted it 32 bits to the left, you'd guarantee that its 31st bit (0-up counting) would always be zero.