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

更新于: 19-6-2020

3000+ 次浏览

开启你的 职业生涯

完成课程认证

开始学习
广告
© . All rights reserved.