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
CodePudding user response:
Well, unsigned
in C is 32bit, you cannot even shift the number you provided once without triggering an overflow, but you have shifted it 8 times and added one more time, like multiplying the number by 257
, you should get the result mod 2^32 == 4294967296
:
unsigned u = 3910796769;
u = u << 8;
this should be 256*u u == 257 * u == 1005074769633 ~= 52422369 (mod 4294967296)
You can test it.
[...]
//Result : 52422369 /* correct (mod 2^32) */
PHP probably uses 64bit integers for the operations, and the result properly fits in 64bit.
$u = 3910796769;
$u = $u << 8;
printf("%u\n",$u);
//Result : 1005074769633
But if you try:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint64_t u = 3910796769;
u = u << 8;
printf("%Lu\n", u);
//Result : 1005074769633
}
you will get the correct result.
CodePudding user response:
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