首先,設定二進位值-
int num = 101;
現在將二進位檔案指派給一個新變數-
binVal = num;
像這樣循環二進位數和基底值,直到值大於0,
while (num > 0) { rem = num % 10; decVal = decVal + rem * baseVal; num = num / 10; baseVal = baseVal * 2; }
以下是將二進位轉換為十進位的程式碼。
現場示範
using System; using System.Collections.Generic; using System.Text; namespace Demo { class MyApplication { static void Main(string[] args) { int num, binVal, decVal = 0, baseVal = 1, rem; num = 101; binVal = num; while (num > 0) { rem = num % 10; decVal = decVal + rem * baseVal; num = num / 10 ; baseVal = baseVal * 2; } Console.Write("Binary Number: "+binVal); Console.Write("Decimal: "+decVal); Console.ReadLine(); } } }
Binary Number: 101 Decimal: 5
以上是將二進制轉換為十進制的 C# 程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!