C# 程式將二進位制轉換為十進位制
首先,設定二進位制值 −
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP