簡體   English   中英

C ++從字符串輸入將二進制轉換為十進制

[英]C++ convert binary to decimal from string input

我有一個問題,因為我有字符串輸入,我想將其轉換為十進制。

這是我的代碼:

#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 ++中輕松地從二進制轉換為十進制?

提前致謝 :))

使用以2為基數的std::strtol 例如,

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

對於蠻力:

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

將該值移位或乘以2,然后將數字加到累加的總和上。

原則上類似於將十進制文本數字轉換為內部表示形式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM