简体   繁体   English

如何将 bitset 转换为字节/uint8 数组?

[英]How do I convert bitset to array of bytes/uint8?

I need to extact bytes from the bitset which may (not) contain a multiple of CHAR_BIT bits.我需要从 bitset 中提取可能(不)包含多个 CHAR_BIT 位的字节。 I now how many of the bits in the bitset I need to put into an array.我现在需要将 bitset 中的多少位放入数组中。 For example,例如,

the bits set is declared as std::bitset < 40> id;位集声明为std::bitset < 40> id;

There is a separate variable nBits how many of the bits in id are usable.有一个单独的变量nBits id有多少位可用。 Now I want to extract those bits in multiples of CHAR_BIT.现在我想以 CHAR_BIT 的倍数提取这些位。 I also need to take care of cases where nBits % CHAR_BIT != 0 .我还需要处理nBits % CHAR_BIT != 0 I am okay to put this into an array of uint8我可以把它放到一个 uint8 数组中

You can use boost::dynamic_bitset , which can be converted to a range of "blocks" using boost::to_block_range .您可以使用boost::dynamic_bitset ,它可以使用boost::to_block_range转换为一系列“块”。

#include <cstdlib>
#include <cstdint>
#include <iterator>
#include <vector>
#include <boost/dynamic_bitset.hpp>

int main()
{
    typedef uint8_t Block; // Make the block size one byte
    typedef boost::dynamic_bitset<Block> Bitset;

    Bitset bitset(40); // 40 bits

    // Assign random bits
    for (int i=0; i<40; ++i)
    {
        bitset[i] = std::rand() % 2;
    }

    // Copy bytes to buffer
    std::vector<Block> bytes;
    boost::to_block_range(bitset, std::back_inserter(bytes));
}

With standard C++11, you can get the bytes out of your 40-bit bitset with shifting and masking.使用标准 C++11,您可以通过移位和屏蔽从 40 位位bitset获取字节。 I didn't deal with handling different values rather than 8 and 40 and handling when the second number is not a multiple of the first.我没有处理不同的值而不是 8 和 40 以及当第二个数字不是第一个数字的倍数时的处理。

#include <bitset>
#include <iostream>
#include <cstdint>

int main() {
    constexpr int numBits = 40;

    std::bitset<numBits> foo(0x1234567890);
    std::bitset<numBits> mask(0xff);

    for (int i = 0; i < numBits / 8; ++i) {
        auto byte =
            static_cast<uint8_t>(((foo >> (8 * i)) & mask).to_ulong());
        std::cout << std::hex << setfill('0') << setw(2) << static_cast<int>(byte) << std::endl;
    }
}

Unfortunately there's no good way within the language, assuming you need for than the number of bits in an unsigned long (in which case you could use to_ulong ).不幸的是,语言中没有好的方法,假设您需要的不仅仅是unsigned long的位数(在这种情况下您可以使用to_ulong )。 You'll have to iterate over all the bits and generate the array of bytes yourself.您必须遍历所有位并自己生成字节数组。

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

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