c++ bitstring to byte

2019-04-17 11:10发布

问题:

For an assignment, I'm doing a compression/decompression of Huffman algorithm in Visual Studio. After I get the 8 bits (10101010 for example) I want to convert it to a byte. This is the code I have:

    unsigned byte = 0;
    string stringof8 = "11100011";
    for (unsigned b = 0; b != 8; b++){
        if (b < stringof8.length())
            byte |= (stringof8[b] & 1) << b;
    }
    outf.put(byte);

First couple of bitstring are output correctly as a byte but then if I have more than 3 bytes being pushed I get the same byte multiple times. I'm not familiar with bit manipulation and was asking for someone to walk me through this or walk through a working function.

回答1:

Using std::bitset

#include <iostream>
#include <string>
#include <bitset>


int main() {

    std::string bit_string = "10101010";
    std::bitset<8> b(bit_string);       // [1,0,1,0,1,0,1,0]
    unsigned char c = ( b.to_ulong() & 0xFF);
    std::cout << static_cast<int>(c); // prints 170

    return 0;
}