std.bitarray examples

Janice Caron caron800 at googlemail.com
Fri May 9 21:07:28 PDT 2008


On 09/05/2008, Me Here <p9e883002 at sneakemail.com> wrote:
> Walter Bright wrote:
>
>  > Me Here wrote:
>  > > Are there any good examples of using std.bitarray around?
>  >
>  > The garbage collector uses it.
>  >
>  > > (And, is my memiry deceiving me or did D have a Bit type once upon a time?)
>  >
>  > Yes, but it was dropped.
>
> Thanks. I got sidetracked away from this. Now I've got back to it I'm still
>  having trouble working out if I can use std.bitarray for my purposes. I need to
>  decompose an unsigned 16-bit value into 8 x 2-bit integers. I C I'd use
>  bitfields. I know and understand why these are not a part of D, but that
>  doesn't help me solve my problem. The data, 900+MB of it is delivered in this
>  packed format and I need to unpack it.
>
>  Can I use std.bitarray to extract these 2-bit numbers? If so, a cluebat as to
>  how would be useful.

std.bitarray is the wrong module to use. It's being deprecated anyway.

What you want is std.bitmanip.

    import std.bitmanip;

    struct A
    {
        ushort n; // unsigned 16-bit number
        mixin(bitfields!(
           uint, "a", 2,
           uint, "b", 2,
           uint, "c", 2,
           uint, "d", 2,
           uint, "e", 2,
           uint, "f", 2,
           uint, "g", 2,
           uint, "h", 2));
    }

Now you've got bitfields, just like in C. Given

    A x;

assigning x.n assigns the whole 16 bit number, while reading and
writing x.a to x.h will read or write the eight individual two-bit
fields.

The documentation for std.bitarray consists in entirety of the
sentence: "Scheduled for deprecation. Use std.bitmanip instead", so
I'm surprised you didn't go there yourself.



More information about the Digitalmars-d mailing list