To convert binary to decimal, here I have used while loop and found the remainder of the binary number, which is the input. After that, multiply the remainders by the base value and add them.
This is how I got the decimal value -
while (val > 0) { remainder = val % 10; myDecimal = myDecimal + remainder* baseVal; val = val / 10; baseVal = baseVal * 2; }
Let’s see the complete code to convert binary to decimal in C#-
LiveDemo
using System; using System.Collections.Generic; using System.Text; namespace Demo { class toBinary { static void Main(string[] args) { int val = 1010, myBinary, remainder; int myDecimal = 0, baseVal = 1; myBinary = val; while (val > 0) { remainder = val % 10; myDecimal = myDecimal + remainder * baseVal; val = val / 10; baseVal = baseVal * 2; } Console.Write("Binary Number : " + myBinary); Console.Write("Converted to Decimal: " + myDecimal); Console.ReadLine(); } } }
Binary Number : 1010 Converted to Decimal: 10
The above is the detailed content of Convert binary to decimal using C#. For more information, please follow other related articles on the PHP Chinese website!