skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    function bcmul_hex($h1, $h2) {
        $dec = bcmul($h1, $h2);
        $hex = '';
        do {    
            $last = bcmod($dec, 16);
            $hex = dechex($last).$hex;
            $dec = bcdiv(bcsub($dec, $last), 16);
        } while($dec>0);
        return $hex;
    }
    
    echo bcmul_hex(0xB5365D09, 0xDEBC252C);
    

    Here is a live example.


  2. 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:

       <?php
    
    $hex1 = "B5365D09";
    $hex2 = "DEBC252C";
    
    // Convert hexadecimal values to decimal
    $dec1 = hexdec($hex1);
    $dec2 = hexdec($hex2);
    
    // Perform multiplication operation
    $result = $dec1 * $dec2;
    
    // Convert result back to hexadecimal
    $hex_result = dechex($result);
    
    // Print result
    echo "Result: $hex_resultn";
    

    This code will output the result of the multiplication as a hexadecimal value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search