How do I convert bitset to array of bytes/uint8?
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 << setfill('0') << setw(2) << static_cast<int>(byte) << std::endl;
}
}
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));
}
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.