1

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?

Jodes
  • 14,118
  • 26
  • 97
  • 156
  • 1
    They are static. Values are kept between calls. Static declaration also used only once so it starts with 1, not executed anymore and kept in memory for next call. – huseyin tugrul buyukisik Aug 03 '13 at 12:40
  • 2
    They are local variables, but they don't have automatic storage duration - `static` means that `x` and `y` always refer to the same instance of the variables, they persist between function calls. –  Aug 03 '13 at 12:41
  • possible duplicate of [What does "static" mean in a C program?](http://stackoverflow.com/questions/572547/what-does-static-mean-in-a-c-program) –  Aug 03 '13 at 12:42

1 Answers1

3

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.
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 2
    C99 6.2.4:3 on a static variable: “Its lifetime is the entire execution”. Your alternative formulation “from (no later than) the function's first invocation until (no earlier than) the last” is not shorter, not simpler, and not equivalent to the official one when the address of the variable is passed around and accessed after the last invocation of the function it is local to. – Pascal Cuoq Aug 03 '13 at 13:03
  • Thank you for the citation. Not having the standard in front of me, I was being deliberately conservative, but your point is well taken. Do you know if it was the same prior to C99? – John Zwinck Aug 03 '13 at 13:18
  • 1
    The corresponding sentence in C89 is “The object exists and retains its last-stored value throughout the execution of the entire program.” – Pascal Cuoq Aug 03 '13 at 13:37