1

So taking the answer with the most upvotes as a base I tried to create a BitSet and set its bits to form the number 478 (111011110) so I did the following:

BitSet set = new BitSet();
set.set(0, true);
set.set(1, true);
set.set(2, true);
set.set(3, false);
set.set(4, true);
set.set(5, true);
set.set(6, true);
set.set(7, true);
set.set(8, false);
System.out.println(bitSetToInt(set));

with the aid of the following method:

public static int bitSetToInt(BitSet bitSet) {
        int bitInteger = 0;

        for (int i = 0; i < 32; i++){
            if (bitSet.get(i)) {
                bitInteger |= (1 << i);
            }
        }
        return bitInteger;
    }

So although I was expecting to get 478 back from this call I am getting 247. Can someone explain me what is going on?

1 Answer 1

1

Bit 0 is the smallest bit (1<<0). You have turned on bits 0, 1, 2, 4, 5, 6 and 7. So your number is 011110111, which is 247.

Sign up to request clarification or add additional context in comments.

1 Comment

right.. I thought of it but when tried it out I forgot the first index 0 so still got the wrong answer. my bad. thanks

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.