mrd
mrd

Reputation: 4699

Bitwise operations in Java: Test if in "1010101111011" a bit is set?

Let's say, I have some user input (as a String) like "11010011011".

Now I want to check if a bit at a bit at a particular position is set (each digit should act as a flag).

Note: I am receiving the user's input as a String.

How can I do that?

Upvotes: 3

Views: 1928

Answers (2)

iabdalkader
iabdalkader

Reputation: 17312

If you want to use bitwise operations, then first convert the string to integer and test with bitmasks:

int val = Integer.parseInt("11010011011", 2);
System.out.println(val & (1<<0)); //First bit
System.out.println(val & (1<<1)); //Second bit
System.out.println(val & (1<<2)); //Third bit
.....

Upvotes: 4

assylias
assylias

Reputation: 328568

You could work with the string as is - say you want to check the first bit on the left:

if (input.charAt(0) == '1') { //

Alternatively if you want to work with a BitSet you can initialise it in a loop:

String input = "11010011011";
BitSet bs = new BitSet(input.length());
int i = 0;
for (char c : input.toCharArray()) {
    if (c == '1') bs.set(i);
    i++;
}

Then to check if the i-th bit is set:

boolean isSet = bs.get(i);

Upvotes: 4

Related Questions