Search code examples
phphexint64uint64

PHP - Converting Hex string to uint64 and to int64


I need to convert a hex string to int64 in PHP, and it should use the last bit as sign instead of hitting the max. For example:

$hex = "eb3dd796efda2409"

and I need the end result to be

-1495802457948019703

I achieve this result on the other languages (python / go) by converting the hex to uint64 and back to int64. I am aware PHP can't do unsigned int64 explicitly.

I found this function using bcmath that correctly convert the hex to string of uint64

 function bchexdec($hex)
 {
     $dec = 0;
     $len = strlen($hex);
     for ($i = 1; $i <= $len; $i++)
         $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));

     return $dec;
 }

But I cant convert the string of uint64 to int64. It will just print the max size instead of falling to negative value. Any idea how to do this?


Solution

  • Finally managed to solve the problem

    unpack("J",hex2bin("eb3dd796efda2409"));
    

    seems hex2bin messed up the endianness so when we tried to do J it resolves correctly Thank you for helping!