I’m attempting to use java’s Bitwise & operator and I think I’m misusing it. Using the below example, with messageAddress of 7 both condition 1 and condition 3 are satisfied. Shouldn’t a messageAddress of 7 just meet the 3rd condition and not the first? Any ideas on how to change the below logic so that messageAddress of 7 would only meet the last condition?
public static final int SLOW = 1;
public static final int SMEDIUM = 2;
public static final int SHIGH = 3;
String messageAddressHex="7";
int messageAddress = Integer.parseInt(messageAddressHex, 16);
if ((messageAddress & SLOW) == SLOW) {
//condition 1 met logic
} else if ((messageAddress & SMEDIUM) == SMEDIUM) {
//condition 2 met logic
} else if ((messageAddress & SHIGH) == SHIGH) {
//condition 3 met logic
}
As it is,
condition 1is all the odd numbers,condition 2is all the numbers with their second least significant bit turned on, andcondition 3is a combination of 1 and 2.I assume that what you really want is to check the two least significant bits as a number between 0 and 3. If that’s the case, you should use:
EDIT:
It’s a much better design to declare another constant as the bit mask:
And then we can write:
The number 3 has two roles –
MASK, which is used as the bitmask to filter only the two last bits, andSHIGH– which is one of the possible values for the last two bits that you want to check.BTW, now you can use a
switch-casestatement instead of theif-else-ifchain: