求计算器中用C#语言编写十进制转换为二进制的代码
发布网友
发布时间:2024-10-24 08:51
我来回答
共2个回答
热心网友
时间:2024-10-31 22:13
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)));
}
/// <summary>
/// 二进制转化为十进制
/// </summary>
/// <param name="dec"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 十进制转化为二进制
/// </summary>
/// <param name="binary"></param>
/// <returns></returns>
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;
}
}
}
热心网友
时间:2024-10-31 22:16
int data= 100;
/*定义一个整形变量data, 并赋给一个十进制数 */
char *ch;
itoa(data,ch,2);
/*把data转换成二进制,并存入在字符串ch中*/
data=strol(ch,NULL,2);
/*data的返回值就是二进制数 */