dongyun9120 2017-05-18 18:17
浏览 78

PHP7按位数按位移位将在PHP中引发ArithmeticError

We're looking to switch to a PHP7 server and are running some compatibility checks on existing code of a website. One of the problems found is with the following function and the Bitwise shifts by a negative number.

Apparently this will throw errors in PHP7. I'll admit I don't fully understand how this arithmetic works, but I was wondering if anyone had a suggesting on how to modify the function to #1 maintain the functionality and #2 become PHP7 compliant.

/**
 * Right shift with zero fill.
 *
 * @param integer $a number to shift
 * @param integer $b number of bits to shift
 * @return integer
 */
public function zeroFill($a, $b){
    return ($a >= 0) ? ($a >> $b) : ($a >> $b) & (PHP_INT_MAX >> ($b - 1));
}
  • 写回答

1条回答 默认 最新

  • doulin6088 2019-03-14 14:21
    关注

    The ArithmeticError is thrown when an mathematical calculation doesn't happen as normally expected, which in this case could lead to values outside of the possible bounds of an integer. (See documentation here)

    Your function is already validating this and limiting the operation for a PHP_INT_MAX, so there is no problem there.

    As to remove the alert message thrown by your verification plugin, you need to cover the function with a try/catch block in order to capture a possible ArithmeticError. This way the function would be like:

    public function zeroFill($a, $b){
        try {
            return ($a >= 0) ? ($a >> $b) : ($a >> $b) & (PHP_INT_MAX >> ($b - 1));
        } catch(ArithmeticError $error) {
            // Do your logic to treat this kind of error
        }
        return $a; // Or return something you would want
    }
    

    Also, using the str_pad is always a good alternative.

    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题