将 BitSet 设置为原始类型?
在Java中,您可以创建一个大小为8的BitSet并将其存储为字节以便输出吗? BitSets 的文档没有提到它。这是否意味着不?
In Java, can you create a BitSet of size 8 and store it as a byte in order to output it? The documentation on BitSets doesn't mention it. Does that mean no?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法将
BitSet
转换为byte
。不过,您可以编写代码来执行您想要的操作。给定一个名为
bits
的BitSet
,如下所示:更新:上面的代码假设您的位从左到右索引为 0 到 7。例如,假设位
01101001
您认为位 0 是最左边的 0。但是,如果您从右到左分配位,那么位 0 将是最右边的 1。在这种情况下,您需要输出|= 1 <<我代替。
You can't cast
BitSet
tobyte
.You can write code to do what you want though. Given a
BitSet
namedbits
, here you go:Update: The above code assumes that your bits are indexed 0 to 7 from left to right. E.g. assuming the bits
01101001
you consider bit 0 to be the leftmost 0. If however you're assigning the bits from right to left then bit 0 would be the rightmost 1. In which case you wantoutput |= 1 << i
instead.没有为此内置任何东西。显然你可以自己实现。
There's nothing built in for that. You could implement that yourself obviously.
位集是
JVM 使用 32 位堆栈单元的位数组,即 JVM 中的每个寄存器存储一个 32 位地址,
我们知道原始布尔值设置为 1 位,但按 32 位处理。布尔数组将被视为
BitSet 中的字节数组,位集的每个组成部分都有一个布尔值
bit set is an array of bits
the JVM uses a 32-bit stack cell ie each register in the JVM stores one 32-bit address
we know that primitive boolean is set to be 1 bit but handled as 32 bit. array of boolean will be considered to be array of bytes
in BitSet each component of the bit set has a boolean value
BitSet 类显然不是为了将其位导出或导入到本机数据类型,并且如果您只想处理单个字节的固定大小,那么它也相当繁重。因此,如果您只想独立操作字节的位然后使用结果字节,那么它可能不是您所需要的。看来您可能只想使用这样的 API:
因此,这种简化的位集的实现可能如下所示:
The BitSet class is obviously not intended to export or import its bits to native datatypes and also quite heavy if you just want to deal with the fixed size of a single byte. It might thus not be what you need if you just want to manipulate the bits of a byte independently and then use the resulting byte. It seems you might just want to use a API like this:
So a implementation of such a simplified bit set could look like this: