简体   繁体   中英

Understanding this 16-bit PRNG

I found this algorithm for a 16-bit PRNG. I don't understand what x, y and t are. What I want to do is use a 16-bit seed to generate multiple random 16-bit values.

If I'm correct, the function shown in that webpage (quoted below) is only pseudo code, since as it stands, it will always generate the same value, since x and y are local variables to the function?

uint16_t rnd_xorshift_32() {
  static uint16_t x=1,y=1;
  uint16_t t=(x^(x<<5)); 
  x=y; 
  return y=(y^(y>>1))^(t^(t>>3));
}

How could the above be modified to read a global variable uint_16_t random (which will have been pre-set with a seed), and then overwrite it with the next random value?

Edit : Thanks, so my understanding of the static variables has been corrected. Would I be correct in saying that x and y are initially set to the seed (both to 1 in the above code) and are then modified to become the subsequent random values? And t is a temporary variable?

The variables x and y are not truly "local" to the function in the sense that you imply. They are declared as static which means while their scope is local to the function (they cannot be accessed by name from outside), their lifetime is that of the entire program. So they will retain their values between calls, which means two things:

  • x and y are in fact the PRNG state.
  • The function is not thread-safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM