简体   繁体   English

C ++位串到字节

[英]c++ bitstring to byte

For an assignment, I'm doing a compression/decompression of Huffman algorithm in Visual Studio. 对于一项任务,我正在Visual Studio中对Huffman算法进行压缩/解压缩。 After I get the 8 bits ( 10101010 for example) I want to convert it to a byte. 获得8位(例如10101010 )后,我想将其转换为字节。 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. 前几对位串正确地作为一个字节输出,但是如果我有3个以上的字节被压入,我会多次获得相同的字节。 I'm not familiar with bit manipulation and was asking for someone to walk me through this or walk through a working function. 我不熟悉位操作,并正在要求某人引导我完成此操作或完成工作功能。

Using std::bitset 使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM