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?
BitSet使用java.util.BitSet存储,以及一组位.
以下是根据设置中的哪些位从inta 转换为a BitSet的int方法:
static BitSet fromInt(int num) {
BitSet bs = new BitSet();
for (int k = 0; k < Integer.SIZE; k++) {
if (((num >> k) & 1) == 1) {
bs.set(k);
}
}
return bs;
}
Run Code Online (Sandbox Code Playgroud)
所以现在你可以做到以下几点:
System.out.println(fromInt(33)); // prints "{0, 5}"
System.out.println(fromInt(97)); // prints "{0, 5, 6}"
Run Code Online (Sandbox Code Playgroud)
而为了完整性,这里是逆向转换:
static int toInt(BitSet bs) {
int num = 0;
for (int k = -1; (k = bs.nextSetBit(k + 1)) != -1; ) {
num |= (1 << k);
}
return num;
}
Run Code Online (Sandbox Code Playgroud)
因此,将两者组合在一起,我们总是得到原始数字:
System.out.println(toInt(fromInt(33))); // prints "33"
System.out.println(toInt(fromInt(97))); // prints "97"
Run Code Online (Sandbox Code Playgroud)
请注意,这使用了基于0的索引,这是更常用的位索引(以及Java中的大多数其他索引).这也更正确.在下面,^表示取幂:
33 = 2^0 + 2^5 = 1 + 32 97 = 2^0 + 2^5 + 2^6 = 1 + 32 + 64
33 -> {0, 5} 97 -> {0, 5, 6}
Run Code Online (Sandbox Code Playgroud)
但是,如果您坚持使用基于1的索引,则可以在上面的代码段中使用bs.set(k+1);和(1 << (k-1)).不过,我会强烈反对这项建议.
^运营商在Java中吗? - 它实际上不是取幂