How to convert BitSet to binary string effectively?

后端 未结 2 585
面向向阳花
面向向阳花 2021-01-12 19:58

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 ex

相关标签:
2条回答
  • 2021-01-12 20:41
    String bitsStr = String.format("%8s", Integer.toBinaryString(bits.toByteArray()[0] & 0xFF)).replace(' ', '0');
    
    0 讨论(0)
  • 2021-01-12 20:44

    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();
    }
    
    0 讨论(0)
提交回复
热议问题