把一个二进制的串转换为整数,如1101 13= 1*2^3+1*2^2+0*2^1+1*2^0 转化为 13=2*(2*(2*(0*2+1)+1)+0)+1 就可以写代码了
代码:
#include <ctype.h>
#include <iostream>
using namespace std;
int main()
{
char p[100];
int n = 0;
cout<<"请输入一个二进制串:"<<endl;
fgets(p,sizeof(p),stdin); //读取完整的一行,输完之后回车,也会记录到数组中
//‘\n’记录回车符之后,fgets()会自动添加一个‘\0’结束输入,所以一般用
// fgets()函数输入字符串末尾会多一个‘\n’,所以 下面的 strlen(p)-1
for(int i=0;i<strlen(p)-1; i++)
{
n = n*2+p[i]-'0';
}
printf("%d\n", n);
system("pause");
}