Sunday, 19 March 2017

Convert binary string to decimal in c#


To convert a binary number to decimal is to look at the bits of the binary number and raise 2 to the power of the index of the “on” bits and add those together. I define an “on” bit as a bit that is 1 as opposed to 0.


For example, the binary number 100 can be looked at as
22 + 0 + 0 = 4
public static void Main()
        {
            var strbinary = "100"; // binary all way read from right to left
            Console.WriteLine(BitStringToInt(strbinary));
            Console.ReadLine();
        }


In the code example below, I first reverse the array to allow the index of our loop (Power) match up with the index of the binary string (the power in which we want to raise 2 to).

private static int BitStringToInt(string bits)
        {
            var reversedbinary = bits.Reverse().ToArray();
           // So we have to get max power of bit , that why we have reversed string value
            var num = 0;
            for (var power = 0; power < reversedbinary.Count(); power++)
            {
                var currentBit = reversedbinary[power];
                if (currentBit == '1')
                {
                    var currentNum = (int)Math.Pow(2, power);
                    num += currentNum;
                }
            }
            return num;
        }

Ouput => 4


No comments:

Post a Comment