C里面将二进制转化为十进制怎么弄??

来源:百度知道 编辑:UC知道 时间:2024/05/17 20:35:07
在C里面以int的格式输入一个数字(在不溢出的情况下),怎么用个比较简单的程序转化为十进制的输出??
这是我自己写的一个,但是太麻烦了...
#include <stdio.h>

int main (void)
{
long int c;//纯是为了防止溢出
int s=1,b=0,r=0,a=1,store;//s是用于储存每位数字,b是最后的十进制输出,r和c是用于计算输入数字的位数,a用于计数,store是储存二进制数的值
float m=0.5;//计算二的幂
printf("please input a number in Bin:\n");
scanf("%ld",&c);
store=c;
while (c>=1){
c=c/10;
r=r+1;
}
while (a<=r){
s=store%10;
store=(store-s)/10;
m=m*2;
b=b+s*m;
a=a+1;
}
printf("c is %d",b);
return 0;
}

/*

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

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<stdio.h>
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;

}

用栈

//结构体顺序栈解决进制转换
#include<stdio.h>
#include<stdlib.h>
#define StackSize 100
typedef char DataType;
typedef struct{
DataType data[StackSize];
int top;
}SeqS