我需要在PHP中添加两个十六进制字符串,并将结果作为十六进制字符串返回。我目前正在使用以下代码:
$s1='f452f5a90e5dc303ab2b1ed139d90782fe98f0694f8c7bf88cade835';
$s2='74392c4cfc18badea29a1048f427c602c56e5d2fdff0860878e67c92';
$sum = hexdec($s1)+hexdec($s2);
$sum1 = dechex ($sum);
echo $sum."<br>";
echo $sum1;
程序返回以下内容作为输出:
3.7970072233566E+67
0
有没有办法在PHP中以更好的方式执行十六进制计算?
答案 0 :(得分:2)
这些数字对于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
答案 1 :(得分: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上进行了测试。
答案 2 :(得分:1)