C ++位串到字节 [英] c++ bitstring to byte

查看:249
本文介绍了C ++位串到字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关的转让,我做一个COM pression / DECOM $ P $霍夫曼算法在Visual Studio中pssion。之后我得到的8位( 10101010 )后我想将其转换为一个字节。这是code我有:

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

第一对夫妇的位串都是正确输出为一个字节但如果我有被推超过3个字节,我得到了相同的字节多次。我不熟悉的位操作,​​并要求别人走我通过这个或通过一个工作功能走路。

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.

推荐答案

使用的std :: bitset的

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

这篇关于C ++位串到字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆