急!!!用V C++把一个16位的二进制数转换为十进制的数,怎么做????

来源:百度知道 编辑:UC知道 时间:2024/05/17 04:41:06
谢谢了!!!
就是像"1001 0010”那种的!,第一种运行起来有一个错误:#error:“eh.h is only for C++!”这是什么意思啊?

#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string BinStr;
int Res=0;

cout <<"Please enter a binary number:";
cin >> BinStr;
for (int i=0;i<BinStr.length();i++)
Res = Res * 2 + (BinStr[i]-'0');
cout << "The result is:" << Res <<endl;
cin.get();
return 0;
}

用库函数还是不用库函数,你的那个所谓的2进制数是字符串还是啥,如果是字符串的话
可以先设置一个有16个元素的数组啦,假设输入时Bnum这个字符串
比如

int values[]=
{1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768};

int value=0;
for(int i=0;i<16;i++)
{
if(Bnum[i]!='0')
{
value=value+values[15-i];
}
}

value就是所要的值