1

I just want to convert integer to binary string using BitSet.

My code is below.

public class BitSetTest {
    public static void main(String[] args) {

        //Method_1
        int value = 10; //0b1010
        String bits = Integer.toBinaryString(value);
        BitSet bs = new BitSet(bits.length());

        for (int i = 0; i < bits.length(); i++) {
            if (bits.charAt(i) == '1') {
                bs.set(i);
            } else {
                bs.clear(i);
            }
        }

        System.out.println(bs); //{0, 2} so 0th index and 2nd index are set. 
        System.out.println(Arrays.toString(bs.toLongArray())); //prints [5]
        System.out.println(Arrays.toString(bs.toByteArray()));

        //Method_2          
        value = 42;
        System.out.println(Integer.toBinaryString(value)); //101010
        BitSet bitSet = BitSet.valueOf(new long[] { value });
        System.out.println(bitSet);
        System.out.println(Arrays.toString(bitSet.toLongArray())); // prints [42]
        System.out.println(Arrays.toString(bitSet.toByteArray()));
    }
}

Q1) What i didn't understand; which is correct approach (Method_1 or Method_2). Method_1 seems to be correct one, but bs.toLongArray() gives different results.

Q2) Could you please explain this api public static BitSet valueOf(long[] longs) accepts array of long values instead of single long ..? And what does really doing with this array.

Java doc says the below; but i really didn't get the meaning.

More precisely, BitSet.valueOf(longs).get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)
for all n < 64 * longs.length.

Please help.

0

1 Answer 1

7

Bits are numbered from the right.

42 = 0b101010
       543210 <-- bit numbers

Hence output of {1, 3, 5}.

Your method #1 numbers bits from the left.

You also don't need to call bs.clear(i), since a new BitSet doesn't have any bits set.

All bits are initially false.


As for how BitSet.valueOf() works, it's fairly simple.

There are two versions for byte data (byte[], ByteBuffer), and two versions for long data (long[], LongBuffer).

A byte consists of 8 bits, and a long consists of 64 bits. The BitSet will then be built with the first N (8 or 64) bits from the first value, the next N bits from the second value, and so forth.

E.g. if you call BitSet.valueOf(new long[] { 1, 2, 3 }), bits 0-63 come from first number, bits 64-127 comes from second number, and bits 128-191 comes from third number, resulting in {0, 65, 128, 129}.

If you call BitSet.valueOf(new byte[] { 1, 2, 3 }), bits 0-7 come from first number, bits 8-15 comes from second number, and bits 16-23 comes from third number, resulting in {0, 9, 16, 17}.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.