Opposite method of math power adding numbers

Posted by adopilot on Stack Overflow See other posts from Stack Overflow or by adopilot
Published on 2010-05-25T18:50:52Z Indexed on 2010/05/25 19:01 UTC
Read the original article Hit count: 541

Filed under:
|
|

I have method for converting array of Booleans to integer. It looks like this

class Program
    {
        public static int GivMeInt(bool[] outputs)
        {
            int data = 0;
            for (int i = 0; i < 8; i++)
            {
                data += ((outputs[i] == true) ? Convert.ToInt32(Math.Pow(2, i)) : 0);
            }
            return data;

        }

        static void Main(string[] args)
        {
            bool[] outputs = new bool[8];
            outputs[0] = false;
            outputs[1] = true;
            outputs[2] = false;
            outputs[3] = true;
            outputs[4] = false;
            outputs[5] = false;
            outputs[6] = false;
            outputs[7] = false;
            int data = GivMeInt(outputs);
            Console.WriteLine(data);
            Console.ReadKey();
        }
   }

Now I want to make opposite method returning array of Booleans values As I am short with knowledge of .NET and C# until now I have only my mind hardcoding of switch statement or if conditions for every possible int value.

public static bool[] GiveMeBool(int data)
        {
            bool[] outputs = new bool[8];

            if (data == 0)
            {
                outputs[0] = false;
                outputs[1] = false;
                outputs[2] = false;
                outputs[3] = false;
                outputs[4] = false;
                outputs[5] = false;
                outputs[6] = false;
                outputs[7] = false;
            }
            //After thousand lines of coed
            if (data == 255)
            {
                outputs[0] = true;
                outputs[1] = true;
                outputs[2] = true;
                outputs[3] = true;
                outputs[4] = true;
                outputs[5] = true;
                outputs[6] = true;
                outputs[7] = true;
            }
            return outputs;
        }

I know that there must be easier way.

© Stack Overflow or respective owner

Related posts about c#

Related posts about math