php十六进制到dec与数学函数返回不同的结果


php hex to dec with math functions is returning different results

为了将长值从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,它有时会返回

2614437288880417560465069440558290446269

有时

2614437288880417560465069440558290446269.00000000000

有什么收获?

在正常情况下,不应输出任何小数部分(包括零)

$dec = bcadd(
    $dec, 
    bcmul(
        strval( hexdec($hex[$i - 1]) ), 
        bcpow('16', strval($len - $i) )
    )
);
// bcadd($left_operand, $right_operand, $scale = 0)

仅仅因为您没有设置bcadd:的第三个参数

规模
此可选参数用于设置结果中小数点后的位数。如果省略,它将默认为使用bcscale()函数全局设置的小数位数,如果尚未设置,则回退到0。

因此,除非您的代码中有明确设置的某些部分:

bcscale(10)

你不会得到复制。

以下是指向bcadd()bcscale()的一些链接。

这是一个例子:

$a = array();
$a['x1'] = bchexdec('c4b03b0a103b7d6ee7199930ad8c27bd');
bcscale(10);
$a['x2'] = bchexdec('c4b03b0a103b7d6ee7199930ad8c27bd');
print_r($a);
// Array
// (
//    [x1] => 261443728880417560465069440558290446269
//    [x2] => 261443728880417560465069440558290446269.0000000000
// )