How portable are bitfields?

Jim Patterson jimp at cognos.UUCP
Sat Sep 15 02:29:33 AEST 1990


In article <508 at mtndew.Tustin.CA.US> friedl at mtndew.Tustin.CA.US (Steve Friedl) writes:
>Hiho folks,
>
>     In our Allegedly Portable Software we have run into some
>code that could naturally use bitfields to nice advantage (in
>readability, at least), and I wonder how reasonably I can rely on
>compilers to support them properly.

I don't know of any "modern" C compilers which don't support
bitfields. However, there are a few things you should look
out for:

1. Signed-ness. It's likely a good idea to avoid plain "int"
bitfields, because some compilers will interpret it as signed while
others will interpret it as unsigned. VAX/VMS C is an example of a
compiler of the former variety. Unfortunately the ANSI X3J11 standard
opted for the "status quo", and didn't attemt to correct this
difference between compilers so plain "int" bitfields are essentially
useless in portable code.  You can use "signed int" to get an
explicitly signed bitfield if you have an ANSI compiler, but this
won't port to most non-ANSI compilers. For maximally portable code,
Use "unsigned int" only when declaring bitfields. 

2. The other main compiler difference you will see is alignment.  Many
compilers, particulary on RISC machines, give any group of bit-fields
"int" alignment and padding, even if you're only using one or two
bits. Other compilers align bit-fields on an addressable-unit (i.e.
char) basis, i.e. they are packed as tightly as possible.  Various
compilers have extensions to change the alignment (e.g.  "unsigned
short field : 5"), but while in common practice they are NOT
ANSI-standard.


-- 
Jim Patterson                              Cognos Incorporated
UUCP:uunet!mitel!sce!cognos!jimp           P.O. BOX 9707    
PHONE:(613)738-1440                        3755 Riverside Drive
                                           Ottawa, Ont  K1G 3Z4



More information about the Comp.lang.c mailing list