取消以下函数的最佳方式是什么?
// Convert a bit-vector to an integer.
int bitvec2int(boolean[] b)
{
[CODE HERE]
}
// Convert an integer x to an n-element bit-vector.
boolean[] int2bitvec(int x, int n)
{
[CODE HERE]
}
或者有没有比传递 boolean 数组更好的方法来完成此类事情?
这出现在 Android 应用程序中,我们需要一个包含 20 个 boolean 值的数组来持久保存,最简单的方法是将整数或字符串写入键值存储。
我将发布我们(Bee和我)编写上述内容的方式作为答案。谢谢!
最佳答案
使用java.util.BitSet
反而。它比处理 boolean[]
快得多。
此外,您应该真正问自己这 20 个 boolean
是否真的应该是 enum
,在这种情况下您可以使用 EnumSet
,这是来自 C 的位字段技术的 Java 解决方案(请参阅:有效的 Java 第 2 版:使用 EnumSet
代替位字段)。
BitSet
与 int
之间的转换
您也可以只使用 BitSet
并删除 int
,但以防万一您需要这些:
static BitSet toBitSet(int i) {
BitSet bs = new BitSet(Integer.SIZE);
for (int k = 0; k < Integer.SIZE; k++) {
if ((i & (1 << k)) != 0) {
bs.set(k);
}
}
return bs;
}
static int toInt(BitSet bs) {
int i = 0;
for (int pos = -1; (pos = bs.nextSetBit(pos+1)) != -1; ) {
i |= (1 << pos);
}
return i;
}
出于教学目的,特意使用了两种不同的技术。为了稳健性,BitSet
到 int
的转换应确保 32 位就足够了。
EnumSet
示例
这个例子是基于书中给出的例子:
import java.util.*;
public enum Style {
BOLD, ITALIC, UNDERLINE, STRIKETHROUGH;
public static void main(String[] args) {
Set<Style> s1 = EnumSet.of(BOLD, UNDERLINE);
System.out.println(s1); // prints "[BOLD, UNDERLINE]"
s1.addAll(EnumSet.of(ITALIC, UNDERLINE));
System.out.println(s1.contains(ITALIC)); // prints "true"
}
}
来自the API :
This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional
int
-based "bit flags."
关于java - 在 Java 中将位 vector ( boolean 数组)转换为整数,并将整数转换为位 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2794802/