Using bitwise & operator and + in Java giving inconsistent results

耗尽温柔 提交于 2019-12-01 16:56:16

问题


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);
    }

回答1:


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);.




回答2:


Operator precedence. + has higher priority than &. Your code

num=num+n&1

Will be executed like

num=(num+n)&1

Look here




回答3:


Operators precedence

int x=n&1;
num=num+x;

and

num=num+n&1;

are different.
You're doing the bitwise & in a different moment.



来源:https://stackoverflow.com/questions/13026029/using-bitwise-operator-and-in-java-giving-inconsistent-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!