将1s和0s的字符串转换为二进制值

时间:2008-09-22 21:46:20

标签: c++ c binary

我正在尝试将来自stdin的1和0的传入sting转换为它们各自的二进制值(其中诸如“11110111”的字符串将被转换为0xF7)。这看起来非常简单,但我不想重新发明轮子所以我想知道C / C ++标准库中是否有任何东西可以执行这样的操作?

6 个答案:

答案 0 :(得分:34)

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char * ptr;
    long parsed = strtol("11110111", & ptr, 2);
    printf("%lX\n", parsed);
    return EXIT_SUCCESS;
}

对于较大的数字,long long版本为strtoll

答案 1 :(得分:14)

您可以使用std :: bitset(如果编译时已知位的长度)
虽然有一些程序你可以将它分解成块并组合。

#include <bitset>
#include <iostream>

int main()
{
    std::bitset<5>  x(std::string("01011"));

    std::cout << x << ":" << x.to_ulong() << std::endl;
}

答案 2 :(得分:9)

您可以使用strtol

char string[] = "1101110100110100100000";
char * end;
long int value = strtol (string,&end,2);

答案 3 :(得分:6)

您可以使用Boost Dynamic Bitset:

boost::dynamic_bitset<>  x(std::string("01011"));
std::cout << x << ":" << x.to_ulong() << std::endl;

答案 4 :(得分:1)

我为此写了一些函数并根据LGPL许可。可以找到here

答案 5 :(得分:0)

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