1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <iostream>
#include <vector>
#include <bitset>
#include <string>
#include <limits>
template< std::size_t N > std::string bitsets_to_string( const std::vector< std::bitset<N> >& data )
{
std::string str_bits ;
for( auto bs : data ) str_bits += bs.to_string() ;
return str_bits ;
}
std::vector< unsigned char > pack_bits( std::string str_bits )
{
static constexpr std::size_t BITS_PER_BYTE = std::numeric_limits< unsigned char >::digits ;
using byte_bits = std::bitset<BITS_PER_BYTE> ;
while( str_bits.size() % BITS_PER_BYTE ) str_bits.push_back( '0' ) ; // pad to multiple of BITS_PER_BYTE
std::vector< unsigned char > result ;
for( std::size_t i = 0 ; i < str_bits.size() ; i += BITS_PER_BYTE )
{ result.push_back( byte_bits( str_bits, i, BITS_PER_BYTE ).to_ulong() ) ; }
return result ;
}
int main()
{
const std::vector< std::bitset<6> > my_bits =
{
0b000001, 0b000011, 0b011000, 0b011111, 0b011001, 0b001010, 0b000000, 0b100000, 0b000000,
0b000000, 0b000000, 0b000000, 0b100110, 0b011111, 0b011000, 0b011100, 0b010011, 0b110110,
// more ...
};
const auto contiguous_bytes = pack_bits( bitsets_to_string(my_bits) ) ;
// ...
}
|