求计算器中用C#语言编写十进制转换为二进制的代码

急急急 谢谢
2025-03-04 03:27:19
推荐回答(2个)
回答1:

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

namespace Sample_02
{
class Program
{
static void Main(string[] args)
{
int a = 39;
Console.WriteLine(DtoB(a));
Console.WriteLine(BtoD(DtoB(a)));
}

///


/// 二进制转化为十进制
///

///
///
static string DtoB(int dec)
{
StringBuilder sb = new StringBuilder();
while (dec > 1)
{
sb.Append(dec % 2);
dec = dec / 2;
}
string binary = "1";
for (int i = sb.Length - 1; i >= 0; i--)
{
binary += sb[i];
}
return binary;
}

///
/// 十进制转化为二进制
///

///
///
static double BtoD(string binary)
{
double dec = 0;
for (int i = 0; i < binary.Length; i++)
{
if(binary[binary.Length - i - 1] == '1')
dec += Math.Pow(2, i);
}
return dec;
}
}

}

回答2:

int data= 100;
/*定义一个整形变量data, 并赋给一个十进制数 */
char *ch;
itoa(data,ch,2);
/*把data转换成二进制,并存入在字符串ch中*/
data=strol(ch,NULL,2);
/*data的返回值就是二进制数 */