Re: I never liked bitfields by some reason.

Oliver Xymoron (oxymoron@waste.org)
Sat, 27 Nov 1999 23:43:36 -0600 (CST)


On Sat, 27 Nov 1999, Pete Zaitcev wrote:

> Now I know why I did not like bitfields. The code below would
> need no #ifdef if it used macroses like
> #define W3_XCVR_MASK 0x00F00000
> or something to that effect...

A better way to do it is to define a map from a structure to a bit
packing, something like this:

{ {0, 5, offsetof(mystruct,mask), sizeof(mystruct->mask), "mask" },
{6, 2, offsetof(mystruct,status), sizeof(mystruct->status), "status" },
...
{-1}
}

etc, where the first digit of the triplet is the bit offset to start at,
the next is the number of bits to copy, and the offsetof bit is an obscure
ANSI C macro for finding element offsets in structures. Make a macro to
construct the entries and you have

{ PACK(0, 5, mystruct, mask),
PACK(6, 2, mystruct, status),
...
PACKEND
};

Then you write little functions like readstruct() and writestruct() for
big and little endian and never think about bitfields, etc., again. Note
that the memory structure mystruct is unpacked so it's faster for software
manipulation and doesn't have to match the hardware structure in layout or
even ordering so you can do a number of things you can't with the bitfield
approach.

--
 "Love the dolphins," she advised him. "Write by W.A.S.T.E.." 

- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.rutgers.edu Please read the FAQ at http://www.tux.org/lkml/