如何使用 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 日

323 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.