使用按位&放大器;运营商和+ Java中给出不一致的结果 [英] Using bitwise & operator and + in Java giving inconsistent results

查看:111
本文介绍了使用按位&放大器;运营商和+ Java中给出不一致的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能有人请解释为什么这些两个Java codeS的片表现不同?第一种正确计算的位数,但第二个只显示1或0非零数字。我不明白发生了什么。

 公共静态无效printNumUnitBits(INT N){
    INT NUM = 0;
    的for(int i = 0; I< 32;我++){
        INT X = N&放大器; 1;
        NUM = NUM​​ + X;
        N = N>>大于1;
        }
     的System.out.println(1位数:+ NUM);
    }    公共静态无效printNumUnitBits(INT N){
    INT NUM = 0;
    的for(int i = 0; I< 32;我++){
        NUM = NUM​​ + N&放大器; 1;
        N = N>>大于1;
        }
     的System.out.println(1位数:+ NUM);
    }


解决方案

在Java中, + 拥有的高precedence &安培; 。你的前pression NUM + N&放大器; 1 将新增 NUM N ,然后采取最低位。

要解决这个问题,尝试使该语句在第二个例子 NUM = NUM​​ +(N&安培; 1);

Could someone please explain why these two pieces of Java codes are behaving differently? First one correctly counts number of bits but the second one just displays 1 or 0 for non-zero numbers. I don't understand whats happening.

    public static void printNumUnitBits(int n){
    int num=0;
    for(int i=0;i<32;i++){
        int x=n&1;
        num=num+x;
        n=n>>>1;
        }
     System.out.println("Number of one bits:"+num);
    }

    public static void printNumUnitBits(int n){
    int num=0;
    for(int i=0;i<32;i++){
        num=num+n&1;
        n=n>>>1;
        }
     System.out.println("Number of one bits:"+num);
    }

解决方案

In Java, + has higher precedence than &. Your expression num+n&1 will add num and n and then take the lowest bit.

To fix this, try making the statement in the second example num=num+(n&1);.

这篇关于使用按位&放大器;运营商和+ Java中给出不一致的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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