如何使用 C# 將十進位制轉換為二進位制?


不妨假設我們想將數字 48 轉換為二進位制。

首先,設定它並使用 / 和 % 運算子,迴圈直到值大於 1 −

decVal = 48;

while (decVal >= 1) {
   val = decVal / 2;
   a += (decVal % 2).ToString();
   decVal = val;
}

現在,按照完整程式碼所示,顯示二進位制的每一位 −

示例

 現場演示

using System;
using System.Collections.Generic;
using System.Text;

namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         int decVal;
         int val;
         string a = "";
         decVal = 48;
         Console.WriteLine("Decimal = {0}", decVal);

         while (decVal >= 1) {
            val = decVal / 2;
            a += (decVal % 2).ToString();
            decVal = val;
         }
         string binValue = "";

         for (int i = a.Length - 1; i >= 0; i--) {
            binValue = binValue + a[i];
         }
         Console.WriteLine("Binary = {0}", binValue);
         Console.Read();
      }
   }
}

輸出

Decimal = 48
Binary = 110000

更新於:2020-6-22

322 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告