要将二进制转换为十进制,在这里我使用了while循环,并找到了二进制数的其余部分,即输入。之后,将余数乘以基值并相加。
这是我做的以获得十进制值-
while (val > 0) { remainder = val % 10; myDecimal = myDecimal + remainder* baseVal; val = val / 10; baseVal = baseVal * 2; }
让我们看看在C#中将二进制转换为十进制的完整代码-
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("\nConverted to Decimal: " + myDecimal); Console.ReadLine(); } } }
输出结果
Binary Number : 1010 Converted to Decimal: 10