Lindsay L
Lindsay L

Reputation: 33

Java: Bitwise operation for flag checking

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.

Upvotes: 3

Views: 2909

Answers (1)

user3969578
user3969578

Reputation:

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.

Upvotes: 2

Related Questions