Bitfield structs and suggestion

Janice Caron caron800 at googlemail.com
Fri Nov 23 06:32:19 PST 2007


I don't like the idea of referring to e.g. n[3..4]. The way I see it,
that's just as error prone as bitshifting. No, what you really want to
do is separate interface from implementation. The interface is, you
want to be able to manipulate bitfields as though they were integers.
The implementation is how you want to store them in a struct. The
whole business of using slice operators pulls implementation details
into the algorithm, where they don't belong.

Howver, it seems to me that we already /have/ bitfields in D. Or at
least, the ability to make them. In the example below, the D usage is
identical to the C usage. All that's different is the way they're
declared. Not only that, it seems to me that the D way offers far more
precision and flexibility. Compare...

C/C++:

    /* define the structure */
    struct S
    {
        unsigned int a : 3;
        unsigned int b : 6;
        unsigned int c : 2;
        unsigned int d : 5;
    }

    /* declare an instance */
    S s;

    /* use the bits */
    s.b = 4;
    s.c = 3;
    s.d = s.b + 1;
    // etc....

D

    /* define the structure */
    struct S
    {
        ushort bits;
	
        uint a() { return (bits >> 13) & 0x07;
        uint b() { return (bits >>  7) & 0x3F;
        uint c() { return (bits >>  5) & 0x03;
        uint d() { return (bits >>  0) & 0x1F;

        void c(uint n) { bits &= 0x1FFF; bits |= (n << 13); }
        void b(uint n) { bits &= 0xE07F; bits |= (n <<  7); }
        void c(uint n) { bits &= 0xFF9F; bits |= (n <<  5); }
        void d(uint n) { bits &= 0xFFE0; bits |= (n <<  0); }
    }

    /* declare an instance */
    S s;

    /* use the bits */
    s.b = 4;
    s.c = 3;
    s.d = s.b + 1;
    // etc....

I'm sure some smart person can come up with a mixin to automate even this!



More information about the Digitalmars-d mailing list