Boost logo

Boost :

From: Jeff Flinn (TriumphSprint2000_at_[hidden])
Date: 2005-06-28 08:16:33


The following is from c.l.c++.

"Vince" <vsix_at_[hidden]> wrote in message
news:42c02e57$0$27313$626a14ce_at_news.free.fr...
> Hi,
>
> I would like to extract or insert some values (of different size) inside
> a buffer.
> I would like to have something like this :
>
>
> BYTE Buffer[207];
>
>
> CBitAPI bitbuf<Buffer, sizeof(Buffer)>;
>
> // Extract different data
> int version = bitbuf.get(0,4); // Extract 4 bits from bit 0
> int whatever = bitbuf.get(4,2); // Extract 2 bits from bit 4
> bool ack = bitbuf.get(6,1) //Extract 1 bit from bit 6
>
> or even better :
>
> int nValue;
> bitbuf.get(4,2, nValue);
>
> DWORD dwValue;
> bitbuf.get(6,4, dwValue);
>
>
> Unfortunately I searched everywhere (boost, google, ) and I didn't found
> anything appropriate.
>
> dynamic_bitset for instance cannot be initialized from an array...

It can according to:
http://www.boost.org/libs/dynamic_bitset/dynamic_bitset.html#header-files

You would use the constructor that takes two input iterators. Since this is
a templated constructor, Buffer elements don't have to be 8bit bytes.

    boost::dynamic_bitset<> bits( &Buffer[0], &Buffer[0] + 207 );

Also see the non-member functions from_block_range,to_block_range and
to_ulong that allow transfer from/to integral data types. The latter could
be used to create a templated function to implement your desired behavior.

// Untested and needs error checking

template< typename T, class BITSET >
T extract_value( BITSET aBits, size_t aBegin, size_t aSize )
{
    // implement size assertions here

    aBits.resize( aBegin + aSize );

    return T((aBits<<aBegin).to_ulong());
}

I'm surprised that this wasn't available for either std::bitset or
boost::dynamic_bitset. Any particular reasons? Would a function with this
ability be a useful addition? Certainly a more efficient implementation
would be desirable.

Jeff Flinn


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk