Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert BitSet to binary string effectively?

I am looking for an efficient way how to easily convert a BitSet to a binary string. Let us say that its usual length would be thousands of bits.

For example, lets have this:

BitSet bits = new BitSet(8);
bits.set(1);
bits.set(3);

And this is the desired result:

String result = toBinaryString(bits);
// expected: result = "01010000"

I have some ideas in general (streams, etc.), but there might be some obvious standard method I am just missing.

like image 769
voho Avatar asked Jan 12 '16 15:01

voho


People also ask

How to convert BitSet to string in Java?

toString() is an inbuilt method of BitSet class that is used to get a string representation of the bits of the sets in the form of a set of entries separated by “, “. So basically the toString() method is used to convert all the elements of BitSet into String.

What is BitSet Java?

BitSet is a class defined in the java. util package. It creates an array of bits represented by boolean values. The size of the array is flexible and can grow to accommodate additional bit as needed. Because it is an array, the bit values can be accessed by non-negative integers as an index.


1 Answers

So this is the most efficient way I have tried so far:

private static class FixedSizeBitSet extends BitSet {
    private final int nbits;

    public FixedSizeBitSet(final int nbits) {
        super(nbits);
        this.nbits = nbits;
    }

    @Override
    public String toString() {
        final StringBuilder buffer = new StringBuilder(nbits);
        IntStream.range(0, nbits).mapToObj(i -> get(i) ? '1' : '0').forEach(buffer::append);
        return buffer.toString();
    }
}

Or other way using more streams:

@Override
public String toString() {
    return IntStream
            .range(0, nbits)
            .mapToObj(i -> get(i) ? '1' : '0')
            .collect(
                    () -> new StringBuilder(nbits),
                    (buffer, characterToAdd) -> buffer.append(characterToAdd),
                    StringBuilder::append
            )
            .toString();
}
like image 112
voho Avatar answered Sep 23 '22 13:09

voho