Determining a set of flags from a ushort

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • HaLo2FrEeEk
    Contributor
    • Feb 2007
    • 404

    #1

    Determining a set of flags from a ushort

    I have a 16x16 board, each square can either be on or off. There is a system of saving which square is on, using a number which, I believe, represents a set of flags. For example, the number 2 means that square (1,1) will be turned on. 4 means that (1,2) is on, and 6 means that both (1,1) and (1,2) are on. See?

    Since there are 16 square in each column, the number goes up to 65536 for single squares, and that means that square (1,16) is on. But let's say that squares (1,1) and (1,16) are both on, the number would be 65538. If all the squares in a row are turned on, the number would be 131070, or all the numbers for each square added together. I put this number in a hex editor as an int32 and looked at the binary representation:

    11111110 11111111 00000001 00000000

    Bitshifted right by one it looks like a nice set of flags:

    11111111 11111111 00000000 00000000

    which can nicely be condensed into an unsigned short. My question is how to get the flags out of it. I confirmed that it is, in fact, flags by turning on the the first, third, and fifth squares in the first column and the result was 42, bitshifted right 1 the resulting bits were:

    00010101 00000000 00000000 00000000

    (I think I might have to make it little endian, though.)

    So, how can I get this to work? How can I extract the on/off value of each bit individually?
  • HaLo2FrEeEk
    Contributor
    • Feb 2007
    • 404

    #2
    Nevermind, guys. I figured this out. It was actually quite simple, which is why it was escaping me. Here's the code I used:

    Code:
    for (int i = 1; i <= 16; i++)
    {
        int x = 1;
        ushort and = (ushort)((int)Math.Pow(2, i) >> 1);
        CheckBox box = (CheckBox)Controls["box" + x + "x" + i];
        bool flagSet = ((flags & and) != 0) ? true : false;
    
        box.CheckState = (flagSet) ? CheckState.Indeterminate : CheckState.Unchecked;
    }
    It works like a dream. Now to expand it to an actual 16x16 grid, instead of only operating on a single column (for testing purposes.)

    You might ask yourself, what use does this have? None, I was just interested in learning how it worked : )

    Comment

    Working...