本文介绍了Java:用于标志检查的按位操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试检查数字是否具有第二位标志(即0000 0010).我的代码如下:
I'm trying to check whether or not a number has the second bit flag (ie 0000 0010). My code is as follows:
int flags = Integer.parseInt(fields[1]);
String strflags = Integer.toBinaryString(flags);
flags = Integer.parseInt(strflags);
int secondBitTest = Integer.parseInt("00000010", 2);
if((flags & secondBitTest) == 2) {
System.out.println("YES");
}
但是我认为我可能做错了,因为当我尝试输入147时,什么也不会返回.
However I think I might be doing this wrong, since when I try to input 147 nothing is returned.
推荐答案
您可以使用我发现的这里.
if (x & (1<<n) != 0) {
//n-th bit is set
}
else {
//n-th bit is not set
}
x是您要检查的数字,n是您要检查的比特.该算法的工作原理是将数字1左移n,然后与x进行与"运算.
x is the number you wish to check, and n is the bit you want to check. The algorithm works by left-shifting the number 1 by n, and AND-ing it with x.
这篇关于Java:用于标志检查的按位操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!