Search code examples
phphexinteger-overflow

PHP prefixing hex summation value with 1?


I am working on something which adds several hexadecimal values (base16).

In a regular C program, I do the following:

uint32_t test1 = 0x5BE0CD19;
uint32_t test2 = 0x3587272B;
uint32_t test3 = 0x1F85C98C;
uint32_t test4 = 0x428A2F98;
uint32_t test5 = 0x61626380;
uint32_t test6 = (test1 + test2 + test3 + test4 + test5);

printf( "%08x \n", test6 );

The result is:

> 54da50e8

However, in PHP (my PHP is 64bit) when I apply the same sum with:

$test1 = 0x5BE0CD19;
$test2 = 0x3587272B;
$test3 = 0x1F85C98C;
$test4 = 0x428A2F98;
$test5 = 0x61626380;
$test6 = ($test1 + $test2 + $test3 + $test4 + $test5);

echo(sprintf( "%08x \n", $test6 ));

I get:

> 154da50e8

Which oddly makes the number an extra character long with a 1 in front of it.

Is there any reasoning to this behavior, and if so how can I prevent it?


Solution

  • Your answers are different because you specifically type your C variables as 32 bits and so the addition overflows, leaving you the result 0x54da50e8. However PHP integers are the same size as installation, in this case 64-bit, so the arithmetic doesn't overflow and you get the correct sum: 0x154da50e8. (Note that your 8 width specification to sprintf is a minimum, hence you get all 9 digits from the result). If you only want a 32-bit result, you need to mask the value of $test6 appropriately i.e.

    $test6 &= (1 << 32) - 1; // 0xFFFFFFFF
    echo(sprintf( "%08x \n", $test6 ));
    

    Output:

    54da50e8