Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

c++ - Concatenate boost::dynamic_bitset or std::bitset

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For the standard bitset, something like:

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

template <size_t N1, size_t 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( a, b ) << endl;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...