Search code examples
crandomcryptographybit-shiftxor

How to pass the output of a function to itself a number of times in RNG?


I'm trying to pass the output of a function in C to itself a number of times but I'm still getting the same answer each time (I tried to pass it by value and by reference I do not know which is the correct one). I have two functions in my program one that does the calculations and it is called xorshift() and the second function has a for loop; to call the function multiple times and it is called foo(). What I want to do exactly is :

I want to pass (f) to the xorshift function and do the xor and shift operations and then return the output, and this output should go to xorshift function and do the xor and shift operations again and get the output and send it again to xorshift function ..etc I want to do this operation for a number of times.

Any thoughts or suggestions on how to do it?

uint64_t foo (uint64_t* j);
uint64_t xorshift (uint64_t*f);

int main(){

uint64_t z=123456789;
foo(&z);

}

//xorshift function
uint64_t xorshift (uint64_t*f){
  uint64_t q=*f;
    q^=q<<13;
    q^=q>>7;
    q^=q<<17;
return q;
}

//foo function
uint64_t foo (uint64_t* j){
    int k=4;
    for (int i=0; i<k; i++){
        xorshift (&j);
}
return j;
}

Solution

  • You just need your inner loop to be:

    j = xorshift(j);
    

    You can change the types throughout to be plain uint64_t and not pointers. You could have used pointers to solve the problem, but you never updated the value through the pointer you had. You copied the value out of it, updated the local copy, and then did nothing with the computed value. The non-pointer version is more idiomatic.