那位牛人,用C语言写一个二进制转化为十进制的程序!!??

2025-03-03 19:17:09
推荐回答(3个)
回答1:

一下两个程序均在VC在编译通过。

/*

如果这个二进制数比较大的话, 大到只能用数组储存这个二进制数,
当然如果大到转化成10进制int存不下的情况那另当别论
*/
#include
#include

int main()
{
char a[33];
int i, num = 0;
scanf("%s", a);

for(i=strlen(a)-1; i>=0; i--)
{
num*=2; /*如果用位运算的话,速度会更快*/
num+=a[i]-'0';
}
printf("%d\n", num);
return 0;
}

/*
如果这个二进制数的位数不超过10位的话
可用这个程序

*/
#include
int main()
{
int num = 0, a, j=1;
scanf("%d", &a);

while(a)
{
num += (a%10) * j;
a /= 10;
j *= 2;
}
printf("%d\n", num);
return 0;

}

回答2:

可以直接输出,数据在计算机内部的储存形式相同

回答3:

/*
*标准程序
*二进制变十进制:
*/
int binary_to_decimal(unsigned short binary[],char decimal[])
{
int iloop;
int jloop;
int flag=0,first=0;
int temp_1,temp_2;
int first_1=0,first_2=0;
int count=2;

memset(decimal,0,NUM_MAX_SIZE*sizeof(char));

for(iloop=0;iloop<64;iloop++)//二进制数内部的循环
{
jloop=NUM_MAX_SIZE-1;
if((flag==0)&&(binary[iloop]==0))//找到第一个1
{
continue;
}
else
{
flag=1;//第一次进入这里说明找到了第一个1

if((first==0)&&(binary[iloop]==1))
{
first=1;
decimal[jloop]=int_to_char(binary[iloop]);
continue;
}
else if((first==1)&&(binary[iloop]==1))
{
while(jloop>0)//对十进制现有的数字遍历*2并作出适当进位
{
if(first_1==0)//用于初次进位值的设定
{
temp_2=1;
first_1=1;
}
temp_1=(ch_to_digi(decimal[jloop])*2)+temp_2;//个位数*2加上1
if(temp_1>=10)//取得进位数
{
temp_2=1;
decimal[jloop]=int_to_char(temp_1-10);
}
else
{
temp_2=0;
decimal[jloop]=int_to_char(temp_1);
}

jloop--;

}
first_1=0;
continue;
}
else if((first==1)&&(binary[iloop]==0))
{
while(jloop>0)//对十进制现有的数字遍历*2并作出适当进位
{
if(first_2==0)//用于初次进位值的设定
{
temp_2=0;
first_2=1;
}
temp_1=(ch_to_digi(decimal[jloop])*2)+temp_2;//个位数*2加上1
if(temp_1>=10)//取得进位数
{
temp_2=1;//有进位
decimal[jloop]=int_to_char(temp_1-10);
}
else
{
temp_2=0;
decimal[jloop]=int_to_char(temp_1);
}

jloop--;

}
first_2=0;
continue;

}
}
}
return 0;
}

int ch_to_digi(char ch)//将数字字符转化成对应的数字
{
switch(ch)
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
default:
return 0;
}
}

char int_to_char(int data)
{
switch(data)
{
case 0:
return '0';
case 1:
return '1';
case 2:
return '2';
case 3:
return '3';
case 4:
return '4';
case 5:
return '5';
case 6:
return '6';
case 7:
return '7';
case 8:
return '8';
case 9:
return '9';
default:
{
printf("数字转化字符出错\n");
exit(1);
}
}
}