Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bitwise & operator and + in Java giving inconsistent results

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);
    }
like image 400
Shimano Avatar asked Oct 23 '12 08:10

Shimano


3 Answers

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

like image 132
Jeff Bowman Avatar answered Oct 01 '22 20:10

Jeff Bowman


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

num=num+n&1

Will be executed like

num=(num+n)&1

Look here

like image 28
zvez Avatar answered Oct 01 '22 19:10

zvez


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.

like image 22
mdm Avatar answered Oct 01 '22 19:10

mdm