Reputation: 180
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:
Upvotes: 1
Views: 3012
Reputation: 153417
rand()
generates a random value [0...RAND_MAX]
of questionable repute - but let us set that reputation aside and assume rand()
is good enough and it is a
Mersenne number (power-of-2 - 1).
Weakness to OP's code: If RAND_MAX == pow(2,31)-1
, a common occurrence, then OP's rand64()
only returns values [0...pow(2,62)). @Nate Eldredge
Instead, loop as many times as needed.
To find how many random bits are returned with each call, we need the log2(RAND_MAX
+ 1). This fortunately is easy with an awesome macro from Is there any way to compute the width of an integer type at compile-time?
#include <stdlib.h>
/* Number of bits in inttype_MAX, or in any (1<<k)-1 where 0 <= k < 2040 */
#define IMAX_BITS(m) ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12))
#define RAND_MAX_BITWIDTH (IMAX_BITS(RAND_MAX))
Example: rand_ul()
returns a random value in the [0...ULONG_MAX]
range, be unsigned long
32-bit, 64-bit, etc.
unsigned long rand_ul(void) {
unsigned long r = 0;
for (int i=0; i<IMAX_BITS(ULONG_MAX); i += RAND_MAX_BITWIDTH) {
r <<= RAND_MAX_BITWIDTH;
r |= rand();
}
return r;
}
Upvotes: 0
Reputation: 6740
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.
Upvotes: 1