为了将长值从 hex
转换为 dec
,我使用了 php.net 评论中的一个函数:
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;
}
为什么函数有时会返回以零结尾的数字?
例如,如果我转换c4b03b0a103b7d6ee7199930ad8c27bd
,它有时会返回
261443728880417560465069440558290446269
有时
261443728880417560465069440558290446269.0000000000
有什么收获?
最佳答案
在正常情况下,this 不应输出任何小数部分(包括零)
$dec = bcadd(
$dec,
bcmul(
strval( hexdec($hex[$i - 1]) ),
bcpow('16', strval($len - $i) )
)
);
// bcadd($left_operand, $right_operand, $scale = 0)
只是因为你没有设置 bcadd
的第三个参数:
scale
This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the bcscale() function, or fallback to 0 if this has not been set.
因此,除非您的代码的某些部分显式设置:
bcscale(10)
你不会得到复制。
这是一个例子:
$a = array();
$a['x1'] = bchexdec('c4b03b0a103b7d6ee7199930ad8c27bd');
bcscale(10);
$a['x2'] = bchexdec('c4b03b0a103b7d6ee7199930ad8c27bd');
print_r($a);
// Array
// (
// [x1] => 261443728880417560465069440558290446269
// [x2] => 261443728880417560465069440558290446269.0000000000
// )
关于php hex to dec with math functions 返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34072224/