Re: Looking to write bitsets to a basic_string
CSAWannabe wrote:
I've got a vector of bitsets with 10 bits in each bitset like this:
std::vector<std::bitset<10> > m_vctBitSets;
std::bitset<10> bsBitSet = 0xF0;
m_vctBitSets.push_back(bsBitSet);
I want to write the vector bitsets to a std::string.. so that there is
no gap between each bitset,i.e. the second bitset in the vector would
start on bit 11 in the std::string. I could also write them to a
buffer something like unsigned char [x]. But prefer to work with
std::string.
Something like this should do the job:
size_t const bitset_size = 10;
std::string output;
unsigned long data = 0;
size_t size = 0;
for (size_t i = 0; i < vec.size(); ++i)
{
if (size + bitset_size > sizeof(data) * 8)
{
// flush ready bytes
while (size >= 8)
{
output += data & 0xFF; // output lowest byte
data >>= 8;
size -= 8;
}
}
data |= vec[i].to_ulong() << bitset_size;
size += bitset_size;
}
--
Alex Shulgin
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]