2

Is there a method or a way to print a bitset as series of bits such as 1001011

For example, the following code:

    BitSet b = new BitSet(6);

    b.set(1);
    b.set(3);
    b.set(4);

    // I want to print b like 101100
    System.out.println(b);

Thanks

Nasser
  • 2,118
  • 6
  • 33
  • 56

2 Answers2

1

Just whip up your own code. With StringBuilder, you can do almost any manipulations with collections. Here is a simple implementation:

            BitSet bi = new BitSet(6);

            bi.set(1);
            bi.set(3);
            bi.set(4);
            StringBuilder s = new StringBuilder();
            for( int i = 0; i < bi.length();  i++ )
            {
                s.append( bi.get( i ) == true ? 1: 0 );
            }

            System.out.println( s );
  • I think OP wants to print it, so it is better to print the bit as `1` or `0`, rather than appending it to the buffer. Also, shouldn't the loop run the other way to consider human endianness? – Kedar Mhaswade Jul 20 '16 at 22:20
  • The question seems to be concerned about printing the bits in a bitset as a series of 1's and 0's. If that were the case, my answer would be correct. About the endianness, to the best of my knowledge, it is only used when you are concerned about significance of bits that is if the data represents some numbers but then I stand corrected. Thank you. – funaquarius24 Jul 22 '16 at 21:43
0

Similar to @funaquarius24 answer, but using java 8 streams:

/**
  * @param bitSet bitset
  * @return "01010000" binary string
  */
public static String toBinaryString(BitSet bitSet) {
  if (bitSet == null) {
    return null;
  }
  return IntStream.range(0, bitSet.length())
      .mapToObj(b -> String.valueOf(bitSet.get(b) ? 1 : 0))
      .collect(Collectors.joining());
}
Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35