I am converting some Javascript code into C# and having a bit of trouble with the Google math longs and how the function. This is actually a version of the Delphi random function - according to my co dev.
In javascript I have this.
function _nextRandom(maxValue, seedValue) {
if (seedValue !== null)
_seed = new goog.math.Long(seedValue);
_seed = _seed.multiply(134775813).add(_one);
_seed = new goog.math.Long(_seed.getLowBitsUnsigned());
return _seed.multiply(new goog.math.Long(maxValue)).getHighBits() >>> 0;
}
In C# I have this - so far.
private int _nextRandom(int maxValue, int seedValue)
{
if (seedValue != 0)
_seed = seedValue;
_seed = _seed * 134775813 + 1;
_seed = (long)((int)_seed); // get lower 32 bits
return (int)(((ulong)_seed * (ulong)maxValue) >> 32); // get upper 32 bits
}
Max value is always 254 and the first time _nextRandom is run seedValue is 1024 every other time afterwards its 0 (in C#) or null (in JS)
Here the output from the C# is correct only for positive values, negative ones are incorrect
Casting the values as byte makes the values nearly match but not exactly.
Does anyone have any ideas why this is happening?


A couple of problems:
_seedto be a 64 bitlong. It should be a 32 bitint._seedandmaxValuetouintbefore performing the 64 bit multiplication.The following C# code replicates the Delphi PRNG:
Obviously this code is not threadsafe but I am sure you already know that. A cleaner implementation would be to wrap this in a class so that you could create distinct instances of the PRNG with their own seed.