Home Ask Login Register

Developers Planet

Your answer is one click away!

Rakim February 2016

Java - BitSet to integer

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);

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?


khelwood February 2016

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.

Post Status

Asked in February 2016
Viewed 2,609 times
Voted 9
Answered 1 times


Leave an answer

Quote of the day: live life