3

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?

3
  • 2
    Cant u use charAt(position) method ? And compare the value is 0/1? Commented Nov 1, 2012 at 15:03
  • Why do you have to use bitwise operations to do this?!?!?! Commented Nov 1, 2012 at 15:04
  • I have no idea what would be the best way to do that. Maybe I would not need bitwise operation. Commented Nov 1, 2012 at 15:10

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

4

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
.....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.