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

时间:2012-11-26 14:23:07

标签: c++

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

编辑:

我用:

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

5 个答案:

答案 0 :(得分:8)

你可以在基数2上使用strtoull()功能(如果你按照链接就有一个例子)。

答案 1 :(得分:3)

如果你有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;
}

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

答案 2 :(得分:1)

以下代码可能是将二进制字符串转换为整数值的最简单方法。不使用biteset或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++;
}

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

将二进制字符串转换为整数,并将二进制字符串(最多64位)转换为long。使用移位功能比pow()效率更高。

#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

string getBinaryString(int value, unsigned int length, bool reverse) {
    string output = string(length, '0');
    if (!reverse) {
        for (unsigned int i = 0; i < length; i++) {
            if ((value & (1 << i)) != 0) {
                output[i] = '1';
            }
        }
    }
    else {
        for (unsigned int i = 0; i < length; i++) {
            if ((value & (1 << (length - i - 1))) != 0) {
                output[i] = '1';
            }
        }
    }
    return output;
}

unsigned long getInteger(const string& input, size_t lsbindex, size_t msbindex) {
    unsigned long val = 0;
    unsigned int offset = 0;
    if (lsbindex > msbindex) {
        size_t length = lsbindex - msbindex;
        for (size_t i = msbindex; i <= lsbindex; i++, offset++) {
            if (input[i] == '1') {
                val |= (1 << (length - offset));
            }
        }
    }
    else { //lsbindex < msbindex
        for (size_t i = lsbindex; i <= msbindex; i++, offset++) {
            if (input[i] == '1') {
                val |= (1 << offset);
            }
        }
    }
    return val;
}

int main() {
    int value = 23;
    cout << value << ": " << getBinaryString(value, 5, false) << endl;
    string str = "01011";
    cout << str << ": " << getInteger(str, 1, 3) << endl;
}