java java中的位掩码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29585720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bit Mask in java
提问by Thanga
Please explain to me how and where to use Bit Mask in java:
请向我解释在 Java 中如何以及在何处使用位掩码:
I don't understand the code below:
我不明白下面的代码:
int bitmask=1;
if ((bitmask & 1) == 1) // what it does
回答by Jean-Fran?ois Savard
The result value for the operator &
is the bitwise AND of the operand values.
运算符的结果值&
是操作数值的按位与。
It means that when applied to two integers (in binary representation), it will result in an integer where each bit will be set to 1 only if both bits at the same position where 1, else to 0.
这意味着当应用于两个整数(以二进制表示)时,它将产生一个整数,其中只有当两个位在同一位置时,每个位都将被设置为 1,否则为 0。
int a = 0b01010111;
int b = 0b11111111;
//result in 0b01010111
System.out.println(a & b);//print 87 which is decimal representation of 0101 0111
Now if you understood my explanation, the example you show us is the equivalent of
现在,如果您理解我的解释,那么您向我们展示的示例相当于
if(true)//because 1 == 1 will always be true.
As doing an &
on two same numbers (1 and 1) will automatically return this number (in that case 1).
由于&
对两个相同的数字(1 和 1)执行操作,将自动返回此数字(在这种情况下为 1)。