Search code examples
phpcbitwise-operatorsbit-shift

Bit shifting in C is different from PHP


I have a question about a small piece of code in C to make the same piece of code work in PHP, it has to do with a bit shift and I can't figure out what's wrong.

C:

unsigned u = 3910796769;
u += u << 8;
printf("%u\n",u); 
//Result : 52422369

PHP:

$u = 3910796769;
$u += $u << 8;
printf("%u\n",$u);
//Result : 1005074769633

Solution

  • In my case, I needed to select elements from an array filled with 32-bit values using a specific formula. The answer from @Eugene Sh helped me do this in PHP.

    $u = 3910796769;
    $u += $u << 8;
    $u = $u & 0xFFFFFFFF
    printf("%u\n",$u);
    //Result : 52422369