PHP无符号右移-故障 [英] PHP Unsigned Right Shift - Malfunctioning

查看:200
本文介绍了PHP无符号右移-故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当使用我的方法在PHP中执行(>>>)无符号右移时,当数字涉及负数时,结果将不正确.

So, when using my method to preform a ( >>> ) unsigned right shift in PHP, the result is incorrect when the numbers involve negatives.

PHP应用程序结果:

PHP Application Results:

INPUT: 10 >>> 3
INPUT: -10 >>> 3
OUTPUT: 1
OUTPUT: 2684354558

JAVA申请结果:

INPUT: 10 >>> 3
INPUT: -10 >>> 3
OUTPUT: 1
OUTPUT: 536870910

(最上面的结果是正确的,并且由Java生成,然后最下面的结果是不正确的,并且由PHP生成)

(The top results are correct and generated by Java and then the bottom results are incorrect and generated by PHP)

只有当PHP中的数字为负数时,它才会失败.

It's only when the number is negative in PHP that it fails.

这些应用程序中使用的班次是:

The shifts being used in those applications is:

请帮助!

PHP转换方法:

function urshift($x, $n){
$mask = 0x40000000;
if ($x < 0){
    $x &= 0x7FFFFFFF;
    $mask = $mask >> ($n-1);
    $ret = ($x >> $n) | $mask;
    $ret = str_pad(decbin($ret), 32, '0', STR_PAD_LEFT);
    $ret[0] = '1';
    $ret = bindec($ret);
} else {
        $ret = (int)$x >> (int)$n;
}
return $ret;

推荐答案

此uRShift较短,可以在32位和64位PHP上正常工作,并且与32位PHP上具有相同大小的Java版本具有相同的结果像Java一样的整数;

This uRShift is shorter, works correctly with 32- and 64-bit PHP and gives the same result as the Java version on 32-bit PHP which has same size ints as Java;

function uRShift($a, $b)
{
    if($b == 0) return $a;
    return ($a >> $b) & ~(1<<(8*PHP_INT_SIZE-1)>>($b-1));
}

> uRShift(-10,3)  
536870910

> uRShift(10,3)
1

这篇关于PHP无符号右移-故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆