"address" of a bitfield
Norman Joseph
norm at oglvee.UUCP
Tue Jul 18 22:52:52 AEST 1989
>From article <2840 at blake.acs.washington.edu>, by wiml at blake.acs.washington.edu (William Lewis):
>
> For the usual reasons, I have to pass the address of a variable to
> a function. (The function needs to read, and possibly modify, any of a
> large number of variables of diverse types.) Unfortunately, many of these
> variables are bitfields, and, obviously, bitfields don't strictly *have*
> an address. Ideally, there is a macro I could write to get something along
> the lines of:
>
> BitFAddr(thing.field, start, offset, width);
Bitfields themselves don't have addresses, but the struct of which
they are a part do. Why not pass a pointer to the whole struct
containing the bitfields? One drawback of this approach is that the
function now needs to know about the struct. Would that be so bad
in your case? If your function needs access to "a large number of
variables of diverse types", it might be worthwhile, if the design
lends itself, to keep these variables together in a struct and pass
a pointer to one of these structs as an argument instead of a long
list of diverse types.
> Does anyone know of an even semi-portable way to do this? Or, if
> there is no portable way, a way that works with Mark Williams C on
> a MSDOS machine?
>From K&R, 1ed., p.45:
getbits( x, p, n ) /* get n bits from position p in x */
unsigned x, p, n;
{
return (( x >> ( p + 1 - n )) & ~( ~0 << n ));
}
As the authors describe it: "...returns (right adjusted) the n-bit field
of x that begins at position p. We assume that bit position 0 is at the
right end and that n and p are sensible positive values."
This should be useful as a starting point.
> Otherwise, I have to assign all my bitfields (many of which are only
> 1 bit wide) to chars, and transcribe them back again after the function
> call, to get the same effect, but with lots of ugly gunk around it...
Even if you needed to do this, you would want to use unsigned ints, since
chars are widened to ints before being passed as function arguments or
used in expressions.
> --- phelliax
> "&(foo.fie.fo -> fum.ziz.clf[grot->thup])"
--
Norm Joseph - Oglevee Computer System, Inc.
UUCP: ...!{pitt,cgh}!amanue!oglvee!norm
/* you are not expected to understand this */
More information about the Comp.lang.c
mailing list