Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent pseudo random between c++ and c#

Tags:

c++

c#

I'm attempting to convert a pseudo rand function from c++ to c# but it doesnt seem to return the correct values. Its important that i use a consistent set for encryption so i cant just use a random number.

this is the function in c++.

int get_pseudo_rand()
{
  return( ((_last_rand = _last_rand * 214013L
     + 2531011L) >> 16) & 0x7fff );
}

and this is my c# alternative

int get_pseudo_rand()
{
  return (((_last_rand = (_last_rand * 214013 + 2531011) >> 16) & 0x7fff));
}

I removed the Ls since c#s int data type is 4 bytes like c++ longs whereas c#s longs are 8 bytes.

the first time the function is run from the seed the answer is consistent with the c++ version but then it begins to diverge.

Any ideas?

like image 740
Calin Leafshade Avatar asked May 09 '26 15:05

Calin Leafshade


1 Answers

You have parenthesized the two statements in a different way that changes their meaning. The C++ code updates _last_rand and then right-shifts the result, the C# code performs the right-shift before updating _last_rand. I've lined the statements up below to make the difference more obvious.

C++:

return (((_last_rand =  _last_rand * 214013L + 2531011L) >> 16) & 0x7fff);

C#:

return (((_last_rand = (_last_rand * 214013  + 2531011 ) >> 16) & 0x7fff));
like image 108
Blastfurnace Avatar answered May 11 '26 04:05

Blastfurnace