Fahmy Arsyaad
Fahmy Arsyaad

Reputation: 9

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 :))

Upvotes: 0

Views: 1741

Answers (2)

Thomas Matthews
Thomas Matthews

Reputation: 57749

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.

Upvotes: 0

Fred Larson
Fred Larson

Reputation: 62113

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

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

Upvotes: 2

Related Questions