我需要从可能(不)包含多个 CHAR_BIT 位的位集中提取字节。我现在需要将位集中的多少位放入数组中。例如,
位集声明为std::bitset < 40> id;
有一个单独的变量nBits
id
中有多少位可用。现在我想以 CHAR_BIT 的倍数提取这些位。我还需要处理 nBits % CHAR_BIT != 0
的情况.我可以将它放入一个 uint8 数组中
最佳答案
您可以使用 boost::dynamic_bitset ,可以使用 boost::to_block_range 将其转换为一系列“ block ” .
#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));
}
关于c++ - 如何将 bitset 转换为字节数组/uint8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8297913/