加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Bitwise op意外地变为负面

发布时间:2020-12-15 04:22:33 所属栏目:Java 来源:网络整理
导读:有人可以向我解释为什么我得到这些结果? public static int ipv4ToInt(String address) { int result = 0; // iterate over each octet for(String part : address.split(Pattern.quote("."))) { // shift the previously parsed bits over by 1 byte resul
有人可以向我解释为什么我得到这些结果?

public static int ipv4ToInt(String address) {
    int result = 0;

    // iterate over each octet
    for(String part : address.split(Pattern.quote("."))) {

        // shift the previously parsed bits over by 1 byte
        result = result << 8;

        System.out.printf("shift = %dn",result);

        // set the low order bits to the current octet
        result |= Integer.parseInt(part);

        System.out.printf("result = %dn",result);
    }
    return result;
}

对于ipv4ToInt(“10.35.41.134”),我得到:

shift = 0
result = 10
shift = 2560
result = 2595
shift = 664320
result = 664361
shift = 170076416
result = 170076550
10.35.41.134 = 170076550

这与我自己进行数学计算时得到的结果相同.

对于ipv4ToInt(“192.168.0.1”),我得到:

shift = 0
result = 192
shift = 49152
result = 49320
shift = 12625920
result = 12625920
shift = -1062731776
result = -1062731775
192.168.0.1 = -1062731775

对于这个,当我手动进行数学运算时,我得到3232235521.

有趣的是:
3232235521 = 11000000101010000000000000000001
当我输入1062731775进入我的Windows calc并按下/ – 按钮时,我得到:
-1062731775 = 22222222222222222222222222222211 110000001010100000000000000000000001

该功能仍然适用于我的目的,但我真的很好奇,为什么当我做最后一点转换时为什么地球结果会变为负值?

解决方法

因为你的情况下位溢出!

在Java中,整数也是32位,范围是-2,147,483,648到2,647.

12625920<< 8越过2 ^ 31-1的限制因此,结果变为负面... 结果只是从-ve侧翻转,因此,从正面留下的任何范围都伴随着来自负面的那么多! 正如大家所建议的那样,你应该使用long变量来避免溢出!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读