简体   繁体   中英

C++ convert binary to decimal from string input

I have a problem because i have string input and i want to convert it to decimal.

Here's my code :

#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;
}

I want to make that last one which is "Decimal" to show converted inputChecker from binary to decimal. Is there any function to easily convert from binary to decimal in c++?

Thanks in advance :))

Use std::strtol with 2 as the base. For example,

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

For brute force:

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';
}

The value is shifted or multiplied by 2, then the digit is added to the accumulated sum.

Similar in principle to converting decimal text digits to internal representation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM