C++:二进制 std::string 到十进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13566785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:29:35  来源:igfitidea点击:

C++: binary std::string to decimal

c++

提问by alessandro

I want to convert 64 bit binary string to 64 bit integer (unsigned). Is there any library function to do that in C++ ?

我想将 64 位二进制字符串转换为 64 位整数(无符号)。在 C++ 中是否有任何库函数可以做到这一点?

Edit:

编辑:

I use:

我用:

main()
{
std::string st = "010111000010010011000100010001110110011010110001010111010010010110100101011001010110010101101010" ;

uint64_t number;
number = strtoull (st.c_str (),NULL,2);
cout << number << " " ;

char ch = std::cin.get();
cout << ch ;


   return 0;
}

回答by Maxim Egorushkin

You can use strtoull()function with base 2 (there is an example if you follow the link).

您可以使用strtoull()基数为 2 的函数(如果您点击链接,则有一个示例)。

回答by ForEveR

If you have C++11 - you can use std::bitsetfor example.

如果你有 C++11 - 你可以使用std::bitset例如。

#include <iostream>
#include <bitset>

int main()
{
    const std::string s = "0010111100011100011";
    unsigned long long value = std::bitset<64>(s).to_ullong();
    std::cout << value << std::endl;
}

or std::stoull

或者 std::stoull

#include <iostream>
#include <string>

int main()
{
    const std::string s = "0010111100011100011";
    unsigned long long value = std::stoull(s, 0, 2);
    std::cout << value << std::endl;
}

回答by maheshmhatre

The following code is probably the simplest way to convert binary string to its integer value. Without using biteset or boost this works for any length of binary string.

以下代码可能是将二进制字符串转换为其整数值的最简单方法。不使用 bitset 或 boost 这适用于任何长度的二进制字符串。

std::string binaryString = "10101010";  
int value = 0;
int indexCounter = 0;
for(int i=binaryString.length()-1;i>=0;i--){

    if(binaryString[i]=='1'){
        value += pow(2, indexCounter);
    }
    indexCounter++;
}

回答by maheshmhatre

You may try this. If you don't need it to be generic, you can specify the type and do away with Number:

你可以试试这个。如果您不需要它是通用的,您可以指定类型并取消 Number:

template <typename Number>
Number process_data( const std::string& binary )
{
    const Number * data_ptr;
    Number data;

    data_ptr = reinterpret_cast<const Number*>(binary.data());
    data = *data_ptr;

    return data;
}