存储位掩码的 int 值 - 提取 1 个值位
我正在计算给定的一组位的 int 等效值并将其存储在内存中。从那里,我想确定原始位掩码中的所有 1 值位。示例:
33 --> [1,6]
97 --> [1,6,7]
在 Java 中实现的想法?
I am calculating the int equivalent of a given set of bits and storing that in memory. From there, I would like to determine all 1 value bits from the original bitmask. Example:
33 --> [1,6]
97 --> [1,6,7]
Ideas for an implementation in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在
BitSet
上使用
java.util.BitSet
来存储一组位。以下是根据
int
中设置的位将int
转换为BitSet
的方法:现在您可以执行以下操作:
为了完整起见,这里是反向转换:
因此,将两者组合在一起,我们总是得到原始数字:
基于 0 的索引
请注意,这使用基于 0 的索引,这是更常用的位索引(并且大多数Java 中的其他所有内容)。这也是比较正确的。在下文中,
^
表示求幂:但是,如果您坚持使用基于 1 的索引,则可以使用
bs.set(k+1);
和上述片段中的 (1 << (k-1))
。然而,我强烈反对这一建议。相关问题
^
运算符的作用是什么? -- 实际上不是求幂On
BitSet
Use
java.util.BitSet
to store, well, a set of bits.Here's how you can convert from an
int
to aBitSet
, based on which bits in theint
is set:So now you can do the following:
And just for completeness, here's the reverse transformation:
So composing both together, we always get back the original number:
On 0-based indexing
Note that this uses 0-based indexing, which is the more commonly used indexing for bits (and most everything else in Java). This is also more correct. In the following,
^
denotes exponentiation:If you insist on using 1-based indexing, however, you can use
bs.set(k+1);
and(1 << (k-1))
in the above snippets. I would advise strongly against this recommendation, however.Related questions
^
operator do in Java? -- it's actually not exponentiation对于位摆弄,java.lang.Integer 有一些非常有用的静态方法。尝试将此代码作为解决您的问题的起始基础:
For bit fiddling, java.lang.Integer has some very helpful static methods. Try this code as a starting base for your problem:
我可以向你展示 C# 实现,Java 应该非常相似。
I can show you C# implementation, Java should be very similar.
如果你想得到这样的数组,你可能需要循环你想要检查的位数
&
整数,每一步移动 1 位。像(伪)的东西:
If you want to get an array like that you'll likely need to loop the number of bits you want to check
&
the integer with a bit shifted 1 for each step.Something like (pseudo):
位运算的变体类似于:
请注意,由于按照您的要求,位从 1 开始索引,因此
bits[0]
未被使用。A bit-crunching variation would be something like:
Note that since the bits are indexed from 1 as you requested,
bits[0]
is left unused.