문제

Okay, got a question. I have assembled a bit mask for options. Basically my page has a list box that allows multiple selections that stores them in a list of integers (their ID value). There are 14 total choices (so ID val 1-15). The reason I am assembling this into a bit mask is because I don't want to hard code in a number in case I want to add options to the database table (where the listbox populates from). Also, I do not want to be sending in 14 parameters to my SQL stored procedure (thus hardcoding in the number 14). I can send in this integer and deconstruction it (later step).

However, right now I need to find out which bits are set in my integer for another reason. Basically I have a property. The get assembles the bit mask from a list of integers (gotten from user selection) and returns an integer of that binary decimal value. Here is my assembled code for the building of the bitmask.

//optsNum is my integer list. This is the list containing the ID nums of the selections.
//so if the user selects the first, second, and fourth option, the list contains 1,2,4 (count 3)
//typeCount is an integer of the amount of options in the list box
int total = 0;
for (int c = 0; c < optsNum.Count(); ++c)
{
    for (int i = 0; i <= typeCount; i++)
    {
        if ((i + 1) == optsNum[c})
            total += (1 << i);
    }
}
return total;

So if the first, second, and fourth are set, my integer is 11. This works, I tested for all selections and it is returning the correct integer/decimal value.

Right now I need help making my set method. This needs to take the decimal/integer that I have, find out which bits are set and place those back into the list. So if I have 11 as my value, I need to put into a list of integers 1,2,4. Can anybody help me?

도움이 되었습니까?

해결책

You should use the BitArray class instead; it does the bitwise operations for you and has a simple interface.
If you will never need more than 32 booleans, you can also use the BitVector32 class, which is smaller.


To answer your question, you need to loop over every bit (using a simple a for loop) and check value & (1 << i) to see whether the ith bit is set.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top