Using bitwise & operator and + in Java giving inconsistent results

Can someone explain why these two pieces of Java code behave differently? The first correctly counts the number of bits, and the second shows only 1 or 0 for nonzero numbers. I do not understand what is going on.

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); } 
+6
source share
3 answers

In Java + has a higher priority than & . Your expression num+n&1 will add num and n , and then take the least significant bit.

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

+5
source

Operator Priority. + has a higher priority than & . Your code

 num=num+n&1 

Will be executed as

 num=(num+n)&1 

Look here

+1
source

operator priority

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

and

 num=num+n&1; 

various.
You do bitwise at another moment.

+1
source

All Articles