PHP 按位与 (&) returns 负数
PHP bitwise AND (&) returns negative number
代码:
echo (5243960811416 & 4040906070209050);
尝试 http://phptester.net/ 结果(右)将是 20407554584
但在我的虚拟主机上它给出了 -1067281896
。
有 20407554584
的解决方法吗?是否有 32 位限制?
经过多方查找,我找到了this answer,并将其转换为PHP:
function BitwiseAndLarge($val1, $val2) {
$shift = 0;
$result = 0;
$mask = ~((~0) << 30); // Gives us a bit mask like 01111..1 (30 ones)
$divisor = 1 << 30; // To work with the bit mask, we need to clear bits at a time
while( ($val1 != 0) && ($val2 != 0) ) {
$rs = ($mask & $val1) & ($mask & $val2);
$val1 = floor($val1 / $divisor); // val1 >>> 30
$val2 = floor($val2 / $divisor); // val2 >>> 30
for($i = $shift++; $i--;) {
$rs *= $divisor; // rs << 30
}
$result += $rs;
}
return $result;
}
用法:
echo BitwiseAndLarge(5243960811416 & 4040906070209050);
代码:
echo (5243960811416 & 4040906070209050);
尝试 http://phptester.net/ 结果(右)将是 20407554584
但在我的虚拟主机上它给出了 -1067281896
。
有 20407554584
的解决方法吗?是否有 32 位限制?
经过多方查找,我找到了this answer,并将其转换为PHP:
function BitwiseAndLarge($val1, $val2) {
$shift = 0;
$result = 0;
$mask = ~((~0) << 30); // Gives us a bit mask like 01111..1 (30 ones)
$divisor = 1 << 30; // To work with the bit mask, we need to clear bits at a time
while( ($val1 != 0) && ($val2 != 0) ) {
$rs = ($mask & $val1) & ($mask & $val2);
$val1 = floor($val1 / $divisor); // val1 >>> 30
$val2 = floor($val2 / $divisor); // val2 >>> 30
for($i = $shift++; $i--;) {
$rs *= $divisor; // rs << 30
}
$result += $rs;
}
return $result;
}
用法:
echo BitwiseAndLarge(5243960811416 & 4040906070209050);