The colon specifies the start of a bit field. The number after the colon is the length in bits that label will take up. The __attribute__((packed)) is a necessary compiler directive, specific to GCC which tells the compiler to make sure that the structure is packed together in the way that it is shown. It also tells the compiler to not rearrange it or expand it in order to make it more efficient to work with by the CPU.

NOTE: that the bit-field example and the shift and mask example are equivalent computationally. One is not necessarily more efficient the other. On one hand, you are writing the mask, in the other, the compiler does this for you.

Using Unions

Lets say we wanted to set the whole structure to zeros or a specific value, we can do this using unions.

What about large data structures? For example, the ID3v1 metadata structure for MP3 files. This datastructure contains title name, artist and many other bits of information about the song to be played. It contains 128 bytes

Field

Length

Description

header

3

"TAG"

title

30

30 characters of the title

artist

30

30 characters of the artist name

album

30

30 characters of the album name

year

4

A four-digit year

comment

28

The comment.

zero-byte

1

If a track number is stored, this byte contains a binary 0.

track

1

The number of the track on the album, or 0. Invalid, if previous byte is not a binary 0.

genre

1

Index in a list of genres, or 255

This is not a bit field, but the same principles stand. This can be turned into a structure as well:

Now, it would take up 128 bytes of memory in to create one of these structures and we want to be conservative. To use use the structure properties, and reduce space usage you can utilize pointers and casting.

Structure of your struct: in gcc, using __attribute__((packed)) is very important, because the compiler may attempt to optimize that structure for speed, by expanding the members of the struct into 32-bits, or it may reorder the members and bit to make easier to do operations on. In these cases, the mapping will no longer work. This is something to consider when using this. This also typically depends on the compiler options for compiling.

Mixing bit fields and members: See the link below on some issues that occurred when you mix bit-fields with variables.