Tuesday, February 4, 2014

Power of bit wise operators - Program to convert bit sequence into integer number

Below is one program written to demonstrate bit processing to one of the fresh programmer. He was trying to code a simple game where the user guess a number between 1-15 and selects whether the guessed number is present in the groups of numbers shown to him. There will be 4 groups of numbers shown to him. 

The program internally shows the numbers which have particular bit positions set. He was doing a big chunk of combinational if statements to decide what is the number guessed based on his selections. This program simplifies it. See the method GetNumberFromBits(). It doesn't cover failure scenarios such as handling a sequence which is more than the size of integer etc..Also all the methods are static.

Seems now a days colleges are not paying attention towards the basics of computer programming which is assembly language which plays with bits.

    class GuessedNumberFinder
    {
        public static void Play()
        {
            byte bitAt1 = GetUserOptionUsingConsole(GetNumbersBasedOnBitPosition(0x0001));
            byte bitAt2 = GetUserOptionUsingConsole(GetNumbersBasedOnBitPosition(0x0002));
            byte bitAt4 = GetUserOptionUsingConsole(GetNumbersBasedOnBitPosition(0x0004));
            byte bitAt8 = GetUserOptionUsingConsole(GetNumbersBasedOnBitPosition(0x0008));
            byte [] bits=new byte[]{bitAt8,bitAt4,bitAt2,bitAt1};
            //int number = Convert.ToInt32(bits.ToString(), 2); //Easiest way
            int result = GetNumberFromBits(bits);
            ShowResult(result);
        }
 
        private static void ShowResult(int result)
        {
            Console.WriteLine();
            Console.WriteLine("Guessed number :{0}", result);
        }
 
        /// <summary>
        /// Converts the sequence of bits to integer number.
        /// </summary>
        /// <param name="bits"></param>
        /// <returns></returns>
        private static int GetNumberFromBits(byte[] bits)
        {
            int result = 0;
            for (int i = 0; i < bits.Length; i++)
            {
                int bitPositionToProcess = (bits.Length - 1) - i;
                result = result | bits[bitPositionToProcess] << i;
            }
            return result;
        }
 
        private static byte GetUserOptionUsingConsole(IEnumerable<byte> numberList)
        {
            Console.WriteLine();
            Console.Write("Press (y/n) if the guessed number present in ");
            foreach (byte number in numberList)
                Console.Write("{0},", number);
            ConsoleKeyInfo key = Console.ReadKey();
            return (key.Key == ConsoleKey.Y) ? (byte)0x1 : (byte)0;
        }
 
        private static IEnumerable<byte> GetNumbersBasedOnBitPosition(int mask)
        {
            for (int index = 0; index < 16; index++)
            {
                if ((index & mask) != 0) yield return (byte)index;
            }
        }
    }

No comments: