Boost logo

Boost :

From: Neil Mayhew (neil_mayhew_at_[hidden])
Date: 2008-05-28 19:59:32


On 26/05/08 02:31 PM Neil Mayhew wrote:
> On 24/05/08 05:45 AM Beman Dawes wrote:
>> Do you have a proposed design for bit-range access?
>
> I was thinking of adding methods to read and write the given bits within
> the value:
>
> value_type endian::bits(std::size_t offset, std::size_t length) const;
> value_type endian::bits(std::size_t offset, std::size_t length,
> value_type value);
>
> struct packet
> {
> ubig24_t abc;
>
> uint_least32_t field_a() const
> {
> return abc.bits(0, 6);
> }
> uint_least32_t field_b() const
> {
> return abc.bits(6, 4);
> }
> uint_least32_t field_c() const
> {
> return abc.bits(10, 14);
> }
> ...
> };

On second thoughts, I've realised this would be easier to read, and
safer, if the bits() methods used start and end rather than offset and
length. Then the values in the methods would match up, and it would be
more obvious if there were gaps or overlaps:

return abc.bits(0, 6);
...
return abc.bits(6, 10);
...
return abc.bits(10, 14);

> A better design might be to specialize Bitfield to accept endians...
>
> If the design used Bitfield instead, there would be one access method
> for both read and write, which would return by value a Bitfield on abc.

Something like this:

Bitfield<0, 6, big32_t> packet::field_a()
{
    return Bitfield<0, 6, big32_t>(abc);
};

You could then write:

packet p;
p.field_a() = 42;
int x = p.field_a();

--Neil


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