Im trying to do a php multiplication of two 32bit long hexadecimal valuey with PHP and it seems it is messing up this calculation, the same happens if i multiplicate it as decimal value.
The calculation is as example:
0xB5365D09 * 0xDEBC252C
Converting to decimal before with hexdec doesnt change anything.
The expected result should be 0x9DAA52EA21664A8C but PHPs result is 0x9DAA52EA21664800
Example:
<?php
$res = 0xB5365D09 * 0xDEBC252C;
echo dechex(intval($res));
?>
What i am doing wrong here?
PHP8.2 running on debian, 64bit AMD.
2
Answers
So, for others to find the answer: Someone stated in the comments to my question, that the result is above the PHP_MAX_INT limit. So when PHP handle it as a FLOAT, there will be some precision of the result lost. I got it to work using bcmath. In my case, i didnt do math with the result any further so i grabbed some piece of code from here, and made a simple function which does what i need. Here you can see a minimum-example:
Here is a live example.
If you’re trying to perform a mathematical operation on a hexadecimal value in PHP, you can use the hexdec function to convert the hexadecimal value to a decimal value, perform the operation, and then use the dechex function to convert the result back to a hexadecimal value.
Here’s an example:
This code will output the result of the multiplication as a hexadecimal value.