How to convert binary to decimal
Take a look at this questions which is very similar but dealing with hex How to convert numbers between hexadecimal and decimal in C#?
Convert.ToInt64(value, 2)
string s=Console.ReadLine();
int b=Convert.ToInt32(s,2);
Console.WriteLine("Input value in base 10 = "+b);
convert any binary to decimal. :)
If you're after a manual way instead of using built in C# libraries, this would work:
static int BinaryToDec(string input)
{
char[] array = input.ToCharArray();
// Reverse since 16-8-4-2-1 not 1-2-4-8-16.
Array.Reverse(array);
/*
* [0] = 1
* [1] = 2
* [2] = 4
* etc
*/
int sum = 0;
for(int i = 0; i < array.Length; i++)
{
if (array[i] == '1')
{
// Method uses raising 2 to the power of the index.
if (i == 0)
{
sum += 1;
}
else
{
sum += (int)Math.Pow(2, i);
}
}
}
return sum;
}
The Convert.ToInt32
method has an overload that accepts a base parameter.
Convert.ToInt32("1001101", 2).ToString();