php hex to dec with math functions 返回不同的结果

标签 php

为了将长值从 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)

你不会得到复制。

这里有一些链接到 bcadd()bcscale() .

这是一个例子:

$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/

相关文章:

php - 在 php/mysql 中将日期时间数据类型转换为日期和时间数据类型

php - 未找到 InvalidArgumentException View [layouts.app]。 Laravel-8 LiveWire-2

php - 如何在给定日期的情况下获取 future 一个月的 Unix 时间戳

php - 以编程方式创建 WooCommerce 订单时设置外部订单 ID

php - 自定义页面 Opencart 的分页

php - MySQL + PHP : select count group by day and user

javascript - 客户端和服务器端编程有什么区别?

php - 仅在 PHPUnit 中需要时才执行 dataProviders?

php - 如何在电子邮件模板中回显 Woocommerce 发货跟踪?

php - Woocommerce:将类别缩略图添加到产品页面的侧边栏