Reputation: 21
I have some issue with a code trying to convert Hex values into decimal one. No matter if it is small or large integer, sometimes, the function returns me the Hex converted to Dec with 8 ceros as trailing. For example: It should return 72500 and returns 72500.00000000 It is randomly and I think the code "is right".
Good one:
stdClass Object
(
[BlockHeight] => 7503088
[BlockHeightHash] => 0x58daab46cb25e887985d8d22d735147a5d92a226316223de04dc7b0ae265f7a7
)
Wrong one:
stdClass Object
(
[BlockHeight] => 7503088.0000000000
[BlockHeightHash] => 0x58daab46cb25e887985d8d22d735147a5d92a226316223de04dc7b0ae265f7a7
)
Procedure
public static function HexDec(string $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 (string)$dec;
return $dec;
//return sprintf('%.0F',$dec);
}
Upvotes: 2
Views: 352
Reputation: 134
Easy way convert hex string to decimal string fro 32-bit version of php
$test = '0x7000005a00000ea5';
$rrrrr = gmp_strval($test);
var_dump($test, $rrrrr);
will return
string '0x7000005a00000ea5' (length=18)
string '8070450918794989221' (length=19)
Upvotes: 0