Java: Bitwise operation for flag checking

别来无恙 提交于 2019-12-22 09:22:08

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!