【问题标题】:Adding large hexadecimal strings in PHP在 PHP 中添加大的十六进制字符串
【发布时间】:2014-07-03 16:26:04
【问题描述】:

我需要在 PHP 中添加两个十六进制字符串并将结果作为十六进制字符串返回。我目前正在使用以下代码:

$s1='f452f5a90e5dc303ab2b1ed139d90782fe98f0694f8c7bf88cade835';
$s2='74392c4cfc18badea29a1048f427c602c56e5d2fdff0860878e67c92';

$sum = hexdec($s1)+hexdec($s2);
$sum1 = dechex ($sum);

echo $sum."<br>";
echo $sum1;

程序返回以下输出:

3.7970072233566E+67 
0

有没有一种方法可以更好地在 PHP 中执行十六进制计算?

【问题讨论】:

  • 您需要手动计算,使用与在纸上计算时相同的操作(将 5 和 2 相加得到 7。将 9 和 3 相加到得到 c。将 8 和 c 相加得到 4,进位 1...)
  • This question 使用 JavaScript 而不是 PHP 提出了基本相同的问题。它的答案也应该适用于此。
  • 如何在程序中做到这一点?两个字符串对应的字符要加吗?
  • 也许这个链接会帮助你php.net/manual/en/function.hexdec.php#90309

标签: php math hex


【解决方案1】:

对于 PHP 的整数数据类型来说,数字太大了。拥有bcmath 扩展名和those nice functions from the PHP manual,您可以使用以下代码:

function bchexdec($hex) {
    if(strlen($hex) == 1) {
        return hexdec($hex);
    } else {
        $remain = substr($hex, 0, -1);
        $last = substr($hex, -1);
        return bcadd(bcmul(16, bchexdec($remain)), hexdec($last));
    }
}

function bcdechex($dec) {
    $last = bcmod($dec, 16);
    $remain = bcdiv(bcsub($dec, $last), 16);

    if($remain == 0) {
        return dechex($last);
    } else {
        return bcdechex($remain).dechex($last);
    }
}

$s1='f452f5a90e5dc303ab2b1ed139d90782fe98f0694f8c7bf88cade835';
$s2='74392c4cfc18badea29a1048f427c602c56e5d2fdff0860878e67c92';

echo bcdechex(bcadd(
    bchexdec($s1), bchexdec($s2)
));

哪个输出:

1688c21f60a767de24dc52f1a2e00cd85c4074d992f7d0201059464c7

【讨论】:

    【解决方案2】:

    my own answer for a similar question 移植到 PHP:

    $ndigits = max(strlen($s1), strlen($s2));
    while (strlen($s1) < $ndigits) $s1 = "0$s1";
    while (strlen($s2) < $ndigits) $s2 = "0$s2";
    $carry = 0;
    $result = "";
    for ($i = $ndigits - 1; $i >= 0; $i--) {
      $d = hexdec(substr($s1, $i, 1)) + hexdec(substr($s2, $i, 1)) + $carry;
      $carry = $d >> 4;
      $result = dechex($d & 15) . $result;
    }
    if ($carry != 0) $result = dechex($carry) . $result;
    

    ideone 上测试。

    【讨论】:

      【解决方案3】:

      事实是dechex的最大回报是:

      ffffffff

      documentation of dechex()

      所以它返回 0 是很正常的 ^^

      希望我能有所帮助:p

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-07
        • 1970-01-01
        • 2019-07-27
        • 2018-09-13
        • 2014-06-11
        • 2010-10-04
        • 2014-05-26
        相关资源
        最近更新 更多