2016-10-21 35 views
0

我有一个问题,因为我有字符串输入,我想将其转换为十进制。C++将二进制从字符串输入转换为十进制

这里是我的代码:

#include <iostream> 
#include <string> 
#include <stdlib.h> 

using namespace std; 

string inputChecker; 
int penghitung =0; 

int main(){ 
    string source = "10010101001011110101010001"; 

    cout <<"Program Brute Force \n"; 
    cout << "Masukkan inputan : "; 
    cin >> inputChecker; 

    int pos =inputChecker.size(); 
    for (int i=0;i<source.size();i++){ 
     if (source.substr(i,pos)==inputChecker){ 
      penghitung +=1; 
     } 
    } 
    if (source.find(inputChecker) != string::npos) 
     cout <<"\nData " << inputChecker << " ada pada source\n"; 
    else 
     cout <<"\nData "<< inputChecker <<" tidak ada pada source\n"; 

    cout <<"\nTotal kombinasi yang ada pada source data adalah " <<penghitung <<"\n"; 
    cout <<"\nDetected karakter adalah " <<inputChecker; 
    cout <<"\nThe Decimal is :" <<inputChecker; 
} 

我要做出最后一个是“小数”,显示从二进制转换inputChecker为十进制。有没有任何函数轻松地从二进制转换为十进制的C + +?

感谢提前:))

+0

使用'std :: bitset'。 –

+0

这篇文章可能会帮助你: http://stackoverflow.com/questions/16043377/conversion-of-string-to-decimal – asantacreu

回答

1

std::strtol使用与2作为碱。例如,

auto result = std::strtol(source.c_str(), nullptr, 2); 
+0

它说结果不命名一种类型先生 –

+0

然后,你不使用C + + 11。你可以使用'long'代替'auto'。 –

+0

现在它说nullptr wasnt声明。我应该使用什么? –

0

为蛮力:

static const std::string text_value("10010101001011110101010001"); 
const unsigned int length = text_value.length(); 
unsigned long numeric_value = 0; 
for (unsigned int i = 0; i < length; ++i) 
{ 
    value <<= 1; 
    value |= text_value[i] - '0'; 
} 

的值被移位或乘以2,则数字被加在累计总和。

原理上类似于将十进制文本数字转换为内部表示。

相关问题