Jump to content

need help with binary operators

- - - - -

  • Please log in to reply
3 replies to this topic

#1
anotheruser

anotheruser

    Learning Programmer

  • Members
  • PipPipPip
  • 44 posts
I have two methods that work but seem needlessly complicated. I'm pretty sure I could make them much easier with binary operators, but I don't know how they work.

I have a boolean array with 9 members on the one hand and an integer on the other. These methods convert one into the other.

Can this be made easier with binary operators?

static bool[] IndexToStatus(int index)

        {

            bool[] res = new bool[9] { false, false, false, false, false, false, false, false, false };

            for (byte i = 8; i >= 0; i--)

            {

                int a = (int)(Math.Pow(2, i));

                if (index >= a)

                {

                    index -= a;

                    res[i] = true;

                }

                if (i == 0)

                    break;

            }

            return res;

        }

static int StatusToIndex(bool[] status)

        {

            int res = 0;

            for (byte i = 0; i < 9; i++)

                if (status[i])

                    res += (int)(Math.Pow(2, i));

            return res;

        }


#2
Momerath

Momerath

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 242 posts
BitArray

#3
anotheruser

anotheruser

    Learning Programmer

  • Members
  • PipPipPip
  • 44 posts
Care to elaborate?

As far as I can see, a BitArray is nothing but a more fancy boolean array.

I can't see how that solves my problem, as that lies not in storing the data but converting it.

#4
Momerath

Momerath

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 242 posts
public BitArray IndexToStatus(int index) {

    return new BitArray(BitConverter.GetBytes(index));

}


public int StatusToIndex(BitArray status) {

    int[] j = new int[1];

    status.CopyTo(j, 0);

    return j[0];

}





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users