有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我可以执行哪些位掩码操作?

我使用的是JavaSWT,它有一系列我可以使用的位标志和操作,但我对它们不熟悉

为了更好地解释,我有自己的风格

style = SWT.A | SWT.B

这基本上转化为风格AB。我知道这是因为

A = 0001
B = 0100
A | B = 0101 (bitwise or)

但我还没有玩到足够多的比特来知道我能做的所有事情,这就是我所知道的

style |= A; // style adds flag A
style &= ~B; // style removes flag B

我是否有+0之类的东西可以使用?用于三值运算

style ?= question ? "+ style A" : "as is, no change"

我在想也许

style = question ? style | A : style;
style = question ? style & ~B : style;

但我不确定

还有什么有用的吗


共 (1) 个答案

  1. # 1 楼答案

    还有排他性OR

    Exclusive OR(又名XOR)简写为一个或另一个,但不是两个。因此,如果将01异或在一起,它将返回一个1。否则a 0。不要忘记,这些位运算符也对boolean值进行操作

    int A = 0b0001;
    int B = 0b0100;
    // A | B = 0101 (bitwise or)
    
    
    style ^= A; // If off, turn on.  If on, turn off.
    
    style = A|B; // 0101
    style ^= A; // style now equals 0100
    style ^= A; // style now equals 0101
    

    你也可以用它交换

    int a = 23;
    int b = 47;
    a ^= b;
    b ^= a;
    a ^= b;
    

    Now a == 47 and b == 23

    最后,位运算符还有另一个用途。克服if语句的短路。下面是一个例子:

    int a = 5;
    int b = 8;
    
    // here a is true, no need to evaluate second part, it is short circuited.
    if (a == 5 || ++b == 7) {
       System.out.println(a + " " + b);
    }
    // but here the second part is evaluated and b is incremented.
    if (a == 5 | ++b == 7) {
      System.out.println(a + " " + b);
    }
    

    我不记得每一次这样使用它,它会导致很难在你的程序中找到错误。但这是一个特点