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

>您可以将strtoull()函数与基数 2 一起使用(如果您点击链接,有一个示例)。

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

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

将二进制字符串转换为整数,将二进制字符串(最多 64 位)转换为长整型字符串。 使用位移比 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;
}
你可以

试试这个。如果你不需要它是泛型的,你可以指定类型并取消 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;
}

最新更新