0

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
                }
4

4 回答 4

4

要使按位掩码有效,您需要使用 2 的幂。

3 = 1 | 2, 因此对于任何x & 3 != 0,x & 1 != 0x & 2 != 0.

更详细地解释一下, 7 是1 + 2 + 4或,在二进制中,111. 请注意,1 位是高位(因此 7 & 1 == 1)。

于 2012-09-13T23:56:10.247 回答
2

实际上,condition 1是所有奇数,condition 2是所有第二个最低有效位打开的数字,并且condition 3是 1 和 2 的组合。

我假设您真正想要的是将两个最低有效位检查为 0 到 3 之间的数字。如果是这种情况,您应该使用:

if ((messageAddress & SHIGH) == SLOW) {
    //condition 1 met logic
} else if ((messageAddress & SHIGH) == SMEDIUM) {
    //condition 2 met logic
} else if ((messageAddress & SHIGH) == SHIGH) {
    //condition 3 met logic
}

编辑:
将另一个常量声明为位掩码是一个更好的设计:

public static final int MASK=3;

然后我们可以写:

if ((messageAddress & MASK) == SLOW) {
    //condition 1 met logic
} else if ((messageAddress & MASK) == SMEDIUM) {
    //condition 2 met logic
} else if ((messageAddress & MASK) == SHIGH) {
    //condition 3 met logic
}

数字 3 有两个作用 - MASK,用作位掩码以仅过滤最后两位,以及SHIGH- 是您要检查的最后两位的可能值之一。

顺便说一句,现在您可以使用switch-case语句而不是if-else-if链:

switch (messageAddress & MASK) {
    case SLOW:
        //condition 1 met logic
        break;
    case SMEDIUM:
        //condition 2 met logic
        break;
    case SHIGH:
        //condition 3 met logic
        break;
}
于 2012-09-13T23:59:27.917 回答
1

的二进制表示7111(注意,全为)。因此,7 & ANYTHING == ANYTHING将始终返回true小于或等于7且大于或等于 的任何值0。例如7 & 3

111 & 011

第一位:0 (1 & 0)
第二位:1 (1 & 1)
第三位:1 (1 & 1)

请注意您是如何再次收到第二个参数的。

于 2012-09-13T23:58:19.367 回答
1
  111 (=7)
& 001 (=1)
----------
  001 (=1)

您可以通过方法检查 int 值的二进制表示Integer.toBinaryString

于 2012-09-13T23:58:55.273 回答