简体   繁体   English

如何将 BitSet 打印为一系列位

[英]How to print BitSet as series of bits

Is there a method or a way to print a bitset as series of bits such as 1001011是否有一种方法或方法可以将位集打印为一系列位,例如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谢谢

Just whip up your own code.只需掀起你自己的代码。 With StringBuilder, you can do almost any manipulations with collections.使用 StringBuilder,您几乎可以对集合进行任何操作。 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 );

Similar to @funaquarius24 answer, but using java 8 streams:类似于@funaquarius24 答案,但使用 java 8 流:

/**
  * @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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM