[英]Why Bitset allows values distinct from 1 and 0?
I try to learn BitSet
collection in java.我尝试在 Java 中学习BitSet
集合。 I have read that it uses bits inside.我读过它在内部使用位。
Each * component of the bit set has a {@code boolean} value位集的每个 * 组件都有一个 {@code boolean} 值
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.我想知道我可以设置不同于 1 和 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:您设置位编号 3、5 和 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).二进制10
是十进制2
(2¹ = 2)。
Binary 00101000
is decimal 40
(2³ + 2⁵ = 8 + 32 = 40).二进制00101000
是十进制40
(2³ + 2⁵ = 8 + 32 = 40)。
BitSet
logically represents a "vector of bits that grows as needed" (javadoc ). BitSet
逻辑上表示“根据需要增长的位向量”(javadoc )。
When you create it via new BitSet()
, you have all bits set to 0 (false).当您通过new BitSet()
创建它时,您将所有位设置为 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);使用set(x)
将位置x (第一个位置为 0)处的位设置为 1(真); eg in your code you enable bits 3, 5 and 9.例如,在您的代码中,您启用了第 3、5 和 9 位。
0 5 10
| | |
000101000100...
toString()
reports the list of bits set to 1, ie 3, 5 and 9 in the example. toString()
报告设置为 1 的位列表,即示例中的 3、5 和 9。
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
). toByteArray()
将BitSet
的内容转换为byte
值序列,每个byte
值包含 8 个连续位的值,以小端顺序(即从BitSet
最少索引开始)。 The output {40, 2}
in your example comes from:您示例中的输出{40, 2}
来自:
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. BitSet.set(int bitIndex)将指定索引处的位设置为 true。
So bitSet.set(9);
所以bitSet.set(9);
flips bit number 9 to 1将位数 9 翻转为 1
On output:在输出:
System.out.println(bitSet);
prints the result of toString which is according to JavaDoc:根据 JavaDoc 打印toString的结果: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.对于此 BitSet 包含处于设置状态的位的每个索引,该索引的十进制表示包含在结果中。 S秒
Arrays.toString(bitSet.toByteArray())
prints byte representation of BitSet. Arrays.toString(bitSet.toByteArray())
打印 BitSet 的字节表示。Step by step, it splits your binary set: 1000101000一步一步,它拆分你的二进制集:1000101000
to bytes: 10 00101000到字节:10 00101000
which is 2 and 40 in decimal.这是 2 和 40 的十进制数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.