问题
I need to extact bytes from the bitset which may (not) contain a multiple of CHAR_BIT bits. I now how many of the bits in the bitset I need to put into an array. For example,
the bits set is declared as std::bitset < 40> id;
There is a separate variable nBits
how many of the bits in id
are usable. Now I want to extract those bits in multiples of CHAR_BIT. I also need to take care of cases where nBits % CHAR_BIT != 0
. I am okay to put this into an array of uint8
回答1:
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
). You'll have to iterate over all the bits and generate the array of bytes yourself.
回答2:
You can use boost::dynamic_bitset, which can be converted to a range of "blocks" using 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));
}
回答3:
With standard C++11, you can get the bytes out of your 40-bit bitset
with shifting and masking. 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.
#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 << static_cast<int>(byte) << std::endl;
}
}
来源:https://stackoverflow.com/questions/8297913/how-do-i-convert-bitset-to-array-of-bytes-uint8