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("\nDecimal: "+decVal);
Console.ReadLine();
}
}
}
输出结果
Binary Number: 101Decimal: 5
以上是 C#程序将二进制转换为十进制 的全部内容, 来源链接: utcz.com/z/356618.html