我如何使用bitarray来做一些最基本的事情,将价值设置为位,而不仅仅是碎片!我开始后悔使用这种称为bitarray的废话。
,我得到了这样的位。public enum RULE
{
NOTHING = 0x0,
FIRST_STEP = 0x1,
FOO_YOU = 0x2,
BAR_FOO = 0x10,
FOO = 0x20,
BAR = 0x40,
FOO_BAR = 0x80,
READY = 0x100,
...//LOTS MORE BITS
FINAL_FLAG_BIT= 0x10000000 //Final bit.. uses the 29th bit.
};
现在说我这样做..
//only use 29 bits to save memory, probably still uses 4 bytes lol.
BitArray rules= new BitArray(29);
//As you can see what I tried to do.
public bool ruleEnabled(RULE i)
{
return rules[(int)i]; //<- this is impossible as it sets BITS not bitmasks.
}
public void setRule(RULE rule, bool b) {
rules.Set((int)rule, b);
}
因此,我浪费了大约30分钟的时间来实施它,而不知道它的局限性很多。.您知道甚至没有任何方法可以将其降低到其价值。
因此,我最终只使用了1个变量(似乎该解决方案既清洁又更快),只需要更改2种方法
CopyTo
和
setRule
才能正常工作。
ruleEnabled
我的问题是我做正确的事吗?为什么Bitarray对此有用?如果它有太多的限制。.您可以完成所有操作,例如已经使用
private int rules; //uses only 29 of the 32 bits.
public bool ruleEnabled(RULE i)
{
int bits = (int)i;
return (rules & bits) == bits;
}
public void setRule(RULE rule, bool set) {
if (set)
rules |= (int)rule;
else
rules &= ~(int)rule;
}
AND
OR
NOT
XOR
&
|
我猜测bitarray最好使用更多的位时,然后任何数据类型都可以表示..用于压缩/加密等。
BitArray可通过索引访问,而不是通过标志访问。 例如,对于长度为29的一点数组,唯一可能的索引范围为0到28。因此,以下索引无效:
~
要使其按预期工作,您必须首先将标志转换为索引。 以下功能可能会有所帮助:
^
rules[RULE.READY] = true; // where READY is equal to 0x100, but the
// bit array's length is only 29.
我希望这有帮助。
为什么我不能再使用1