1

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?

Uday Babariya
  • 1,031
  • 1
  • 13
  • 31
Reynaldi Wijaya
  • 111
  • 3
  • 13
  • You have to check the sign bit first (most significant bit). If the number is positive, convert it using the function above. If it is negative, perform a [2's complement conversion](https://en.wikipedia.org/wiki/Two%27s_complement), that is, invert the number (bitwise), compute it's value, then add 1. – Aziz Mar 15 '18 at 05:04

1 Answers1

0

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!

Reynaldi Wijaya
  • 111
  • 3
  • 13