我可以执行哪些位掩码操作?
What are the bit mask operations that I can perform?
我正在使用 java SWT,它有一堆我可以使用的位标志和操作,但我不熟悉它们。
为了更好的解释,我有一个风格
style = SWT.A | SWT.B
这基本上转化为具有样式 A AND B。我知道这是因为
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;
但我不确定。
还有什么有用的吗?
还有异或。
异或(又名 XOR)在 shorthand 中表示, 一个或另一个但不是两个 。因此,如果您将 0
和 1
异或在一起,它将 return 和 1
。否则一个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);
}
我不记得每次都以这种方式使用它,这会导致很难在您的程序中找到错误。但这是一个功能。
我正在使用 java SWT,它有一堆我可以使用的位标志和操作,但我不熟悉它们。
为了更好的解释,我有一个风格
style = SWT.A | SWT.B
这基本上转化为具有样式 A AND B。我知道这是因为
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;
但我不确定。
还有什么有用的吗?
还有异或。
异或(又名 XOR)在 shorthand 中表示, 一个或另一个但不是两个 。因此,如果您将 0
和 1
异或在一起,它将 return 和 1
。否则一个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);
}
我不记得每次都以这种方式使用它,这会导致很难在您的程序中找到错误。但这是一个功能。