好吧,我在服务器上实现 Blake 哈希时遇到了一些问题,因为这不是一台 x64 服务器机器。我编写了一个小函数,利用 BC 库的强大功能来执行按位移位操作。
<?php
echo '左移测试<br />';
bprint('1', decbin(1));
bprint('1 << 32 (失败)', decbin(1 << 32)); bprint('shiftleft(1, 32) (成功)', dec2bin(shiftleft('1', '32'))); echo '<br />';
echo '右移测试<br />';
bprint('9223372036854775808', dec2bin('9223372036854775808'));
bprint('9223372036854775808 >> 63 (失败)', decbin(9223372036854775808 >> 63));
bprint('rightshift(9223372036854775808, 63) (成功)', decbin(rightshift('9223372036854775808', '63')));
function shiftleft($num, $bits) {
return bcmul($num, bcpow('2', $bits));
}
function rightshift($num, $bits) {
return bcdiv($num, bcpow('2', $bits));
}
function bprint($title, $content) {
echo $title . '<br />' . str_pad($content, 64, '0', STR_PAD_LEFT) . '<br />' . PHP_EOL;
}
function dec2bin($dec) {
for ($b = '', $r = $dec; $r >1;) {
$n = floor($r / 2);
$b = ($r - $n * 2) . $b;
$r = $n; }
return ($r % 2) . $b;
}
?>