views:

261

answers:

3

Hey,

what is the best way to concatenate 2 bitsets?

For example i've got

boost::dynamic_bitset<> test1( std::string("1111") );
boost::dynamic_bitset<> test2( std::string("00") );

they should be concatenated into a thrid Bitset test3 which then holds

111100 

Solutions should use boost::dynamic_bitset. If the solution works with std::bitset, it would be nice too. There should be a focus on performance when concatenating the bits.

UPDATE: I've compared both methods (stringmethod from me and Neil and shiftmethod from messenger) and the stringmethod was a lot faster (factor 10++). Code here: http://pastebin.com/HfpfYfy8

I hope Pastebin is ok for posting long code-listings. If there is a better way please contact me.

A: 

For getting started, i'll add a possible solution by myself. The following code uses the possibility to construct bitsets with std::string and to generate a std::string from a bitset.

boost::dynamic_bitset<> test1( std::string("1111") );
boost::dynamic_bitset<> test2( std::string("00") );

std::ostringstream bitsetConcat;
bitsetConcat << test1 << test2;
boost::dynamic_bitset<> test3( bitsetConcat.str() );

std::cout << test3 << std::endl;

This works, but there must be other, more performant solutions...

MOnsDaR
+2  A: 

For the standard bitset, something like:

#include <bitset>
#include <string>
#include <iostream>
using namespace std;

template <int N1, int N2 >
bitset <N1 + N2> concat( const bitset <N1> & b1, const bitset <N2> & b2 ) {
    string s1 = b1.to_string();
    string s2 = b2.to_string();
    return bitset <N1 + N2>( s1 + s2 );
}

int main() {
    bitset <4> a( string("1010") );
    bitset <2> b( string("11") );
    cout << concat<4,2>( a, b ) << endl;
}
anon
A: 

Here is a stab at a solution. Not sure if it compiles.

typedef boost::dynamic_bitset<> Bits;

Bits Concatenate(const Bits& first, const Bits& second)
{
    Bits value(first);

    //Increase the size of the bit buffer to fit the data being placed in it
    value.resize(first.size() + second.size());
    value <<= second.size();
    value |= second;
    return value;
}
messenger
The above code does not work because when using the operator|= both bitsets must have the same length.It would work when initing a copy of the second too and resizing it. I've uploaded the code to pastebin if anyone is interested:http://pastebin.com/cguqaMgS
MOnsDaR