简体   繁体   English

怪异的移位行为

[英]Weird bit shifting behaviour

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. 我希望下面的所有3条语句表明测试i中的第j位是否已设置。
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());
                }
        }

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. 如果将1左移j,然后用它屏蔽i,则必须将结果与1左移j而不是1的结果进行比较。

In other words the condition should be 换句话说,条件应该是

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

Or just "!= 0" would be fine. 或者只是“!= 0”就可以了。

(i & ( 1<<j))==1 is false unless j == 0 , because ((1<<j) & 1 == 0) == (j != 0) (*). 除非j == 0 ,否则(i & ( 1<<j))==1为假,因为((1<<j) & 1 == 0) == (j != 0) (*)。

This is simply not equivalent to the other expressions. 这根本不等同于其他表达式。


(*) Well, j % 32 == 0 / j % 32 != 0 ; (*)好吧, j % 32 == 0 / j % 32 != 0 ; the second operand is masked. 第二个操作数被屏蔽。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM