2

C#.NET:

public int NextRandom(int n) {
    int n2 = (n + 7) * 3;
    n = ((int)((uint)n >> 8) | n << 24);
    n ^= ((int)((uint)n >> 7) & 0x3FF) * ((int)((uint)n >> 22) & 0x3FF) + 5 * (n2 + 3);
    return n;
}
NextRandom(1337); 

C# RETURN: 956321482

PHP:

public function NextRandom($n) {
     $n2 = ($n + 7) * 3;
     $n = ((int)(abs($n) >> 8) | $n << 24);
     $n ^= ((int)(abs($n) >> 7) & 0x3FF) * ((int)(abs($n) >> 22) & 
0x3FF) + 5 * ($n2 + 3);
     return $n;
}
NextRandom(1337);

PHP RETURN: 22431157962

What is wrong in my PHP code? Tanks for help.

SOLVED: I add

$n &= 0xFFFFFFFF;

to put the integer back into 32-bit range.

2
  • try shaving away some of the code, or break them down into less complicated lines, and use the console logging feature to see where they differ in each step Commented Nov 26, 2018 at 20:56
  • 1
    Most likely it's because you're using (uint) casting in one and abs() in the other, or one of your constants are different. Commented Nov 26, 2018 at 20:57

1 Answer 1

3

the result of your operation is 22431157962 the value that PHP shows

But the max value an int(32bit) can show is 2147483647, so it can not fit in the return type(int) you have defined, try changing the return type to long(64 bit number) (+any other cast if needed) and you should be fine, not a master at PHP but i think PHP is using 64 bit number in this case

Just for more debug info, the way to debug this is look at HEX values
956321482 = 0x39004ECA
22431157962 = 0x539004ECA

If you look close the first 32bit are same, but your number needs more than that

Sign up to request clarification or add additional context in comments.

4 Comments

With $n &= 0xFFFFFFFF; NextRandom(1337); It show the same Number but ( NextRandom(1000); ) show different: (C#: -402638061) (PHP: 3892329235)
That is the same problem, PHP uses 64 bit so the sign bit is 63th bit counting from zero, considering your 0xFFFFFFFF mask, sign bit is zero and number is positive, but in c# you are using 32 bit number and bit 31 which is sign bit can be 1 and produce negative number, like your case, again either use 64 bit number or simply cast c# output to uint to produce positive number and ignore sign bit.
I cant change the C#, i need the code from C# to PHP
I told you where problem is, but to fixed it, it is a PHP question that I am not good at, but if I were to suggest an ugly method i say do this, check if bit 31 is 1 or not, if it is, use OR and set upper 32 bit of PHP output to 1, you will have a negative number same as C#

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.