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");
}
However I think I might be doing this wrong, since when I try to input 147 nothing is returned.
You can check if any bit is set using this code that I found here.
if (x & (1<<n) != 0) {
//n-th bit is set
}
else {
//n-th bit is not set
}
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.
来源:https://stackoverflow.com/questions/31921546/java-bitwise-operation-for-flag-checking