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

标签 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++ 中将二进制转换为十进制吗?

提前致谢:))

最佳答案

使用std::strtol以2为底。例如,

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

关于C++将字符串输入的二进制转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40180167/

相关文章:

javascript - 十进制正则表达式和空字符串

batch-file - 批处理脚本中的小数

c++ - 检索 DLL 名称,而不是调用应用程序名称

c++ - 使用删除函数从字符串中删除字符 - C++

C++ 二进制转十进制?

haskell - Haskell 中的二进制数

python - 截断十进制值

c++ - gets() 函数在 Visual Studio 2015 社区中不可用

c++ - Enable_if 作为模板参数

C - 将 char 转换为 int 以对输出执行按位操作