Java:检查一个位是 0 还是 1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1092411/
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
Java: Checking if a bit is 0 or 1 in a long
提问by Ande Turner
What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?
您将使用什么方法来确定表示 2^x 的位是 1 还是 0 ?
采纳答案by Jon Skeet
I'd use:
我会用:
if ((value & (1L << x)) != 0)
{
// The bit was set
}
(You may be able to get away with fewer brackets, but I never remember the precedence of bitwise operations.)
(您可能可以使用较少的括号来逃脱,但我从不记得按位运算的优先级。)
回答by Noldorin
For the n
th LSB (least significant bit), the following should work:
对于n
第 LSB(最低有效位),以下应该有效:
boolean isSet = (value & (1 << n)) != 0;
回答by Artur Soler
The value of the 2^x bit is "variable & (1 << x)"
2^x 位的值是“变量 & (1 << x)”
回答by schnaader
Bit shiftingright by x and checking the lowest bit.
右移x 并检查最低位。
回答by ThibThib
You can also use
你也可以使用
bool isSet = ((value>>x) & 1) != 0;
EDIT: the difference between "(value>>x) & 1
" and "value & (1<<x)
" relies on the behavior when x is greater than the size of the type of "value" (32 in your case).
编辑:“ (value>>x) & 1
”和“ value & (1<<x)
”之间的区别取决于x大于“值”类型的大小(在您的情况下为32)时的行为。
In that particular case, with "(value>>x) & 1
" you will have the sign of value, whereas you get a 0 with "value & (1<<x)
" (it is sometimes useful to get the bit sign if x is too large).
在这种特殊情况下,使用 " (value>>x) & 1
" 将获得值的符号,而使用 " value & (1<<x)
"获得 0 (如果 x 太大,有时获取位符号很有用)。
If you prefer to have a 0 in that case, you can use the ">>>
" operator, instead if ">>
"
如果您希望在这种情况下使用 0,则可以使用“ >>>
”运算符,而不是“ >>
”
So, "((value>>>x) & 1) != 0
" and "(value & (1<<x)) != 0
" are completely equivalent
所以,“ ((value>>>x) & 1) != 0
”和“ (value & (1<<x)) != 0
”是完全等价的
回答by finnw
Another alternative:
另一种选择:
if (BigInteger.valueOf(value).testBit(x)) {
// ...
}
回答by Ande Turner
I wonder if:
我怀疑是否:
if (((value >>> x) & 1) != 0) {
}
.. is better because it doesn't matter whether value is long or not, or if its worse because it's less obvious.
.. 更好,因为值是否长无关紧要,或者更糟,因为它不那么明显。
Tom Hawtin - tackline Jul 7 at 14:16
汤姆霍廷 - 抢断 7 月 7 日 14:16
回答by Yannick Motton
You might want to check out BitSet: http://java.sun.com/javase/6/docs/api/java/util/BitSet.html
您可能想查看 BitSet:http: //java.sun.com/javase/6/docs/api/java/util/BitSet.html
回答by typeseven
回答by Miguel Alonso Mosquera
My contribution - ignore previous one
我的贡献 - 忽略前一个
public class TestBits {
public static void main(String[] args) {
byte bit1 = 0b00000001;
byte bit2 = 0b00000010;
byte bit3 = 0b00000100;
byte bit4 = 0b00001000;
byte bit5 = 0b00010000;
byte bit6 = 0b00100000;
byte bit7 = 0b01000000;
byte myValue = 9; // any value
if (((myValue >>> 3) & bit1 ) != 0) { // shift 3 to test bit4
System.out.println(" ON ");
}
}
}