简体   繁体   English

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

[英]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. 我要使最后一个为“十进制”,以显示从二进制转换为十进制的inputChecker。 Is there any function to easily convert from binary to decimal in c++? 是否有任何函数可以在c ++中轻松地从二进制转换为十进制?

Thanks in advance :)) 提前致谢 :))

Use std::strtol with 2 as the base. 使用以2为基数的std::strtol 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. 将该值移位或乘以2,然后将数字加到累加的总和上。

Similar in principle to converting decimal text digits to internal representation. 原则上类似于将十进制文本数字转换为内部表示形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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