我有一个像:
这样的整数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
我忘记了如何做到这一点,以及这种类型的操作是什么,
由于
答案 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));