开发者

How to set BitArray to set specfic Bits based on value?

开发者 https://www.devze.com 2023-03-18 11:02 出处:网络
How do I use BitArray to do a few things such the most basic, setting a value to bits, not just bits! I am starting to regret ever using this crap called BitArray.

How do I use BitArray to do a few things such the most basic, setting a value to bits, not just bits! I am starting to regret ever using this crap called BitArray.

Say I got bits such as this.

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.
};

Now say I do this..

//only use 29 bits to save memory, 开发者_C百科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);
}

So I wasted around 30 minutes implementing this without knowing one of it's many limitations.. You know there isn't even any way to cast it down to it's value.. without using CopyTo

So I ended up using just 1 variable (seems this solution is both cleaner and faster) and only had to alter 2 methods setRule and ruleEnabled for it to work properly.

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;
}

My question is did I do the right thing? and why is the BitArray ever useful for? if it has so much limitations.. you can do all of it's operations such as AND OR NOT XOR already with & | ~ ^

I guess BitArray is best used when you are dealing with more bits then any datatype can represent.. for compressions/encryptions etc..


BitArray is accessed by index, not by flags. For instance, for a bit array with length 29, the only possible indexes range from 0 through 28. Thus, the following is invalid:

rules[RULE.READY] = true; // where READY is equal to 0x100, but the
                    // bit array's length is only 29.

To make it work as intended, you must convert the flag to an index first. The following function may help:

public static int FlagToIndex(int flag){
   int i=0;
   if(flag==0)return i;
   while((flag&1)==0){
     flag>>=1;
     i++;
   }
   return i;
}

With this function you can now properly index the bit array:

rules[FlagToIndex((int)RULE.READY)] = true;

I hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消