javascript - Converting JS Using Google.Math.Long to C# -


i converting javascript code c# , having bit of trouble google math longs , how function. version of delphi random function - according co dev.

in javascript 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# have - far.

private int _nextrandom(int maxvalue, int seedvalue) {     if (seedvalue != 0)         _seed = seedvalue;      _seed = _seed * 134775813 + 1;     _seed = (long)((int)_seed); // lower 32 bits     return (int)(((ulong)_seed * (ulong)maxvalue) >> 32); // upper 32 bits } 

max value 254 , first time _nextrandom run seedvalue 1024 every other time afterwards 0 (in c#) or null (in js)

here output c# correct positive values, negative ones incorrect

casting values byte makes values match not exactly.

does have ideas why happening?

a couple of problems:

  • you have declared _seed 64 bit long. should 32 bit int.
  • you need cast _seed , maxvalue uint before performing 64 bit multiplication.

the following c# code replicates delphi prng:

private static int _seed = 0;  private static int _nextrandom(int maxvalue, int seedvalue) {     if (seedvalue != 0)         _seed = seedvalue;     _seed = _seed * 0x08088405 + 1;     return (int)(((ulong)(uint)_seed * (uint)maxvalue) >> 32); } 

obviously code not threadsafe sure know that. cleaner implementation wrap in class create distinct instances of prng own seed.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -