按位运算,如何检查0或1?

时间:2012-08-30 16:40:59

标签: java

我有一个像:

这样的整数
0x10000010

我想知道某个特定位是1还是0.例如,像:

int number = 0x10000010;
for (int i = 0; i < 8; i++) {
    if (ith bit == 1) {
        System.out.println("bit " + i + " is 1.");
    } else {
        System.out.println("bit " + i + " is 0.");
    }
}

---- output ----
bit 0 is 1
bit 1 is 0
bit 2 is 0
bit 3 is 0
bit 4 is 0
bit 5 is 0
bit 6 is 1
bit 7 is 0

我忘记了如何做到这一点,以及这种类型的操作是什么,

由于

2 个答案:

答案 0 :(得分:8)

如果未设置该位,则

number & (1 << i)将为0,如果为,则为非零。

答案 1 :(得分:3)

与dty的答案类似

int number = 0b10000010; // you are assuming this is binary not hex.
for (int i = 0; i < 8; i++) {
    if((number >> i) & 1 != 0)
        System.out.println("bit " + i + " is 1.");
     else 
        System.out.println("bit " + i + " is 0.");
}

int number = 0b10000010; // you are assuming this is binary not hex.
for (int i = 0; i < 8; i++) 
    System.out.println("bit " + i + " is " + ((number >> i) & 1));