C ++从字符串输入将二进制转换为十进制

时间:2016-10-21 15:13:32

标签: c++ binary decimal

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

这是我的代码:

#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 ++中是否有任何函数可以轻松地从二进制转换为十进制?

提前致谢:))

2 个答案:

答案 0 :(得分:1)

使用std::strtol和2作为基础。例如,

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

答案 1 :(得分: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,然后将数字加到累计和中。

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

相关问题