mardi 22 septembre 2020

Generating random 64/32/16/ and 8-bit integers in C

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:

  1. Why is it shifted 31 bits? I thought rand() generated a number between 0-32767 which is 16 bits, so wouldn't that be 48 bits?
  2. Why do we say | (or) b on the second to last line?



Aucun commentaire:

Enregistrer un commentaire