Search code examples
c#phpoverflowuint32uint

How to force PHP to treat a number like a uint


I have some C# code that looks like this:

uint a = 0x9E3779B9;
a += (uint)(url[k + 0] + (url[k + 1] << 8) + (url[k + 2] << 16) + (url[k + 3] << 24));

After that code, a == 228 452 386

Now I'm trying to translate this C# code to PHP, but in PHP the number doesn't overflow the same way:

$a = 0x9E3779B9;
$a += ($url[$k+0] + ($url[$k+1] << 8) + ($url[$k+2] << 16) + ($url[$k+3] << 24));

After that code, $a == 4 523 419 682

In both cases "url" is treated as an array of ascii values. The returns the same results until the moment $a is added to the result of the second line. At that point, the C# uint overflows to ~228 million. PHP gets "clever" and comes up with the "right" answer.

But I want the overflowed answer that C# gives. What should I do?


Solution

  • Add a $a &= 0xFFFFFFFF to put the value back into the 32-bit range after you've done the +=.

    (See: http://www.ideone.com/6BR0U)