"address" of a bitfield (idea 1)

brian.g.beuning bgbg at cbnewsd.ATT.COM
Wed Jul 19 09:33:55 AEST 1989


>     Does anyone know of an even semi-portable way to do this?

How about something like this?  If you want to describe the
bitfields of struct x

	struct x {
		int	a: 2;
		int	b: 3;
		int	c: 5;
	} y;

for each field (using 'a' as an example) do,

	1. set all of 'y' to zero (using memset or bzero)
	2. set y.a = ~0 (all 1's, compiler will truncate unless
		your compiler allows bitfield's larger than int)
	3. see which bits of y have changed (from zero) and set
		start, offset, and width appropriately.

For step 3 use an array of int's that overlay 'struct x'
(or equivalently a
	union _x {
		struct x	main;
		int		array[ sizeof(struct x) / sizeof(int) ];
	} _y;
).
search _y.array[] for a non-zero entry (this gives start)
then search this int for the first '1' and the last '1'
(these give offset and width).

The question in my mind is the big- vs. little-endian problem.
Is it possible that there could be two strings of 1's if the
bitfield crosses a char or short boundary?

The above must be done every time your program executes in
an initialization routine.

Brian Beuning



More information about the Comp.lang.c mailing list