Weird bit shifting behaviour

IUnknown

I was attempting the powerset problem with iteration and bit shifting.
There is a particular behaviour I am unable to comprehend.
I would have expected all the 3 statement below to indicate testing if jth bit in i is set.
Why are the results different then?

private static void printSubsetInBit(Integer[] arr) {
                for(int i=0;i<(1<<arr.length);i++){
                    List<Integer> pack=new ArrayList<Integer>();
                    for(int j=0;j<arr.length;j++){
                        //if(((i>>j)&1)==1){ -->>>> WORKS
                        //if((i & ( 1<<j))>0){-->>>> WORKS
                        if((i & ( 1<<j))==1){ -->>>> DOES NOT WORK
                            pack.add(arr[j]);
                        }
                    }
                    System.out.println(pack.toString());
                }
        }
Willis Blackburn

If you left-shift 1 by j and then use it to mask i, you have to compare the result to the result of left-shifting 1 by j, not to 1.

In other words the condition should be

((i & (1 << j)) == (1 << j))

Or just "!= 0" would be fine.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related