Bit Manipulation in Java - Conditionally Toggling Bits Based on Bit Values?

David :

I have 8 Objects we will call "lights". Each light can be toggled on or off (0 or 1). Each light has an index (0-7).

I have no familiarity with Bitwise operations in Java, but I think the following code checks whether the light is on or off properly:

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

I am currently facing the problem of not being able to turn on all of the lights. For example, if light 0 is on and I turn on light 1, light 1 will say it is on, but light 0 will then say it is off. That is with the following code:

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

I know I am setting it improperly. I just can't figure out how to. This stuff doesn't exactly compute in my brain. I've read up on all of the Bitwise operators and it still doesn't really make sense to me. Can anyone please explain to me what I am doing wrong?

erickson :

Your approach to "turning on the light" is okay.

You might think it is broken because there is a bug in how you test whether a "light" is on. Let's break it down:

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

Starting with the innermost parentheses, you intersect index with 1. This results in shifting value one bit if the index is odd, and doing nothing if the index is even.

Then you compare the result of the shift with 1.

If value is 3 and index is zero, you get an erroneous false result. If value is greater than three, you get false regardless of index, which may be erroneous.

An expression like this will give intended results:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=3655&siteId=1