C bit structure

Levi Pearson levi at cold.org
Thu Mar 19 20:35:01 MDT 2009

Alec Shaw <shaw.alec at gmail.com> writes:

> I want to implement a struct that is 4 bytes in size that has
> alternate bit fields
> similar to the following.  The struct below is 12 bytes in size.
> Any suggestions on how create a similar structure of only 4 bytes.
> I want to overlay the structure on a character stream.

Byron gave you the answer, but I thought I'd elaborate a bit.  

The C language standard doesn't define how structs are stored in memory,
so compilers are free to decide on their own how to store them.  The
reason they don't tend to do what you expected by default is that modern
computers access data in word-size chunks, so access to individual
struct elements is faster if they start on word boundaries.  Thus,
padding is introduced by the compiler to align the elements.

Since the standard doesn't define how structs are stored, there's no
standard way to tell your compiler how to change its struct layout, and
any code that does so is inherently compiler-specific.  So if you're not
using gcc, you'll have to look into your compiler documentation.

You might also want to keep in mind byte-ordering in case this character
stream is coming from another computer.


More information about the PLUG mailing list