c++ bitstring to byte

匆匆过客 提交于 2019-12-06 14:51:52

问题


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


来源:https://stackoverflow.com/questions/26656878/c-bitstring-to-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!