Fahmy Arsyaad Fahmy Arsyaad - 1 month ago 6
C++ Question

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

Answer

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

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