Java中的位操作——基于位值的条件切换位



我有8个对象,我们称之为"lights"。每个灯光都可以打开或关闭(0或1(。每个灯光都有一个索引(0-7(。

我不熟悉Java中的Bitwise操作,但我认为以下代码可以检查灯是否正确打开或关闭:

int value = 128;
int index = light.getIndex();
boolean lightIsOn = (value >> (index & 0x1) == 1);

我目前面临的问题是无法打开所有的灯。例如,如果灯0打开,而我打开灯1,灯1会说它打开,但灯0会说它关闭

if (!lightIsOn) {
value = (value | 1 << index);
}

我知道我设置不正确。我就是想不出该怎么做。这些东西在我的大脑中无法准确计算。我已经阅读了所有的Bitwise运算符,但它对我来说仍然没有意义。有人能向我解释我做错了什么吗?

你"开灯"的方法还可以。

你可能认为它坏了,因为在测试"灯"是否亮起的过程中有一个错误

boolean lightIsOn = (value >> (index & 0x1) == 1);

从最里面的括号开始,index与1相交。这导致如果索引是奇数,则将value移位一位,如果索引是偶数,则不执行任何操作。

然后将移位的结果与1进行比较。

如果value为3,index为零,则会得到错误的false结果。如果value大于3,则无论index如何,都会得到false,这可能是错误的。

这样的表达式将给出预期的结果:

boolean lightIsOn = ((value >>> index) & 1) == 1;

我通常会对这类事情进行调试。虽然在脑海中整理它很好,但有时看到实际的比特集也很好。在我看到它正常工作后,我评论掉了中间调试语句:

public class StackOverflowTest {
int value = 128;
public static void main(String[] args){
StackOverflowTest test = new StackOverflowTest();
System.out.println(Integer.toBinaryString(test.value));
System.out.println("is 7 on? " + test.lightIsOn(7));
System.out.println("n-- turnOff(7) --");
test.turnOff(7);
System.out.println("is 7 on? " + test.lightIsOn(7));
System.out.println(Integer.toBinaryString(test.value));    
System.out.println("n-- turnOn(4) --");
test.turnOn(4);
System.out.println("is 4 on? " + test.lightIsOn(4));
System.out.println(Integer.toBinaryString(test.value));
}
boolean lightIsOn(int index) {
//    System.out.println(Integer.toBinaryString(value));
//    System.out.println(Integer.toBinaryString(index & 0x1));
//    System.out.println(Integer.toBinaryString(value >> index));
//    System.out.println(Integer.toBinaryString((value >> index) & 0x1));
//    System.out.println(Integer.toBinaryString(value));
//    return value >> (index & 0x1) == 1; // this is not working
return ((value >> index) & 0x1) == 1;
}
void turnOff(int index) {
if (lightIsOn(index)) {
//      System.out.println(Integer.toBinaryString(value));
//      System.out.println(Integer.toBinaryString(1 << index));
//      System.out.println(Integer.toBinaryString(value));
value = (value ^ (1 << index));
}
}
void turnOn(int index) {
if (!lightIsOn(index)) {
//      System.out.println(Integer.toBinaryString(value));
//      System.out.println(Integer.toBinaryString(1 << index));
//      System.out.println(Integer.toBinaryString(value));
value = (value | (1 << index));
}
}
}

希望它能对您有所帮助。

如果你的灯号小于32。

你可以试着对每一盏灯使用比特计算。例如:

light1: 1
light2: 2
light3: 4
light4: 8
light5: 16
light6: 32
light7: 64
light8: 128
So If the mumber is 2: that will be light2
So If the mumber is 3: that will be light1 and light2
So If the mumber is 15: that will be light1,light2,light3,light4

最新更新