suggestion: joining two bitsets

It is quite disappointing that C++11 cannot join two bitsets.
For example, I am doing Huffman encoding/decoding. I have obtained the code word for every input element. Now I want to join them together.

I suggest std::bitset should be treated like std::string. All string operations such as string concatenation, sub-string extraction, string search, etc., are supported for bitset in the next version C++ standard.
> All string operations such as string concatenation, sub-string extraction, string search, etc., are supported for bitset

Forstring operations, convert the std::bitset<> to a std::string.
http://www.cplusplus.com/reference/bitset/bitset/to_string/

There is also an explicit conversion from std::string to std::bitset<>
http://www.cplusplus.com/reference/bitset/bitset/bitset/


Concatenate bitsets:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <bitset>
#include <type_traits>
#include <limits>
#include <string>

constexpr std::size_t ULONGLONG_BITS = std::numeric_limits<unsigned long long>::digits ;

template< std::size_t N1, std::size_t N2 >
typename std::enable_if< (N1+N2) <= ULONGLONG_BITS, std::bitset<N1+N2> >::type // efficient for small sizes
cat( const std::bitset<N1>& a, const std::bitset<N2>& b ) { return ( a.to_ullong() << N2 ) + b.to_ullong() ; }

template< std::size_t N1, std::size_t N2 > 
typename std::enable_if< ( (N1+N2) > ULONGLONG_BITS ), std::bitset<N1+N2> >::type 
cat( const std::bitset<N1>& a, const std::bitset<N2>& b ) { return std::bitset<N1+N2>( a.to_string() + b.to_string() ) ; }

int main()
{
    const std::bitset<12> a( "101100111000" ) ;
    const std::bitset<20> b( "11110000111100001111" ) ;
    const std::bitset<50> c( "11111000001111100000111110000011111000001111100000" ) ;
    std::cout << a << " cat " << b << " == " << cat(a,b) << '\n' 
              << b << " cat " << c << " == " << cat(b,c) << '\n' ;
}

http://coliru.stacked-crooked.com/a/d56285796dbf09b8
Bitsets represent fixed sets of bits.

If you want a dynamic collection of bits, use std::vector<bool> or boost::dynamic_bitset.
Topic archived. No new replies allowed.