简体   繁体   中英

Why Bitset allows values distinct from 1 and 0?

I try to learn BitSet collection in java. I have read that it uses bits inside.

Each * component of the bit set has a {@code boolean} value

I wrote a small application:

BitSet bitSet = new BitSet();
bitSet.set(9);
bitSet.set(5);
bitSet.set(3);
System.out.println(bitSet);
System.out.println(Arrays.toString(bitSet.toByteArray()));

I was wondered that I can put value different from 1 and 0.

Also I don't understand the output:

{3, 5, 9}
[40, 2]

Please explain me the usage of this collection?

You set the bits number 3, 5 and 9:

byte#      1                 0
index  … 9 8   7 6 5 4 3 2 1 0
value  … 1 0   0 0 1 0 1 0 0 0

Binary 10 is decimal 2 (2¹ = 2).

Binary 00101000 is decimal 40 (2³ + 2⁵ = 8 + 32 = 40).

BitSet logically represents a "vector of bits that grows as needed" (javadoc ).

When you create it via new BitSet() , you have all bits set to 0 (false).

0    5    10
|    |    |
000000000000... (virtually infinite sequence)

Using set(x) you set to 1 (true) the bit at position x (where the first position is 0); eg in your code you enable bits 3, 5 and 9.

0    5    10
|    |    |
000101000100...

toString() reports the list of bits set to 1, ie 3, 5 and 9 in the example.

toByteArray() converts the contents of the BitSet to a sequence of byte values, each containing the value of 8 contiguous bits, in little-endian order (ie starting from least indices in the BitSet ). The output {40, 2} in your example comes from:

 7      0   15     8    <- position in BitSet
 |      |   |      |
{00101000 , 00000010}   <- toByteArray(), binary
    |          |
{  40     ,    2    }   <- toByteArray(), decimal

Hope this helps.

BitSet.set(int bitIndex) sets the bit at the specified index to true.

So bitSet.set(9); flips bit number 9 to 1

On output:

  • System.out.println(bitSet); prints the result of toString which is according to JavaDoc:

for every index for which this BitSet contains a bit in the set state, the decimal representation of that index is included in the result. S

Step by step, it splits your binary set: 1000101000

to bytes: 10 00101000

which is 2 and 40 in decimal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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