Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 135 ยท Structures and Unions

Bit-Fields

Learn C bit-fields: struct members with a width in bits, packing flags and small values, signedness, overflow, zero-width fields and portability limits.

Some values need far less room than a whole int. A flag is on or off: one bit. A day of the month fits in 5 bits (0โ€“31), a month in 4 (0โ€“15), an RGB color channel at reduced quality in 5 or 6. When you store millions of records, or squeeze settings into a single word, those wasted bits add up. A bit-field is a struct member declared with an explicit width in bits, and the compiler packs neighboring bit-fields tightly into the same storage unit.

Bit-fields read like normal struct members: you assign and compare them with ordinary syntax, and the compiler generates the shifting and masking for you. The price is that much of their layout is implementation-defined, so they're great for compact data inside one program and risky for anything that must match an exact bit pattern. This lesson shows both sides.

Declaring bit-fields

Put a colon and a width after a member's name. The width is the number of bits the member occupies:

C A packed date

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The three fields need 5 + 4 + 12 = 21 bits, which fit in a single 32-bit storage unit, so the packed struct is 4 bytes instead of 12. Everything else is ordinary struct syntax: designated initializers, the dot operator, compound assignment.

The rules for the declaration:

  • The member's type must be bool (or _Bool), signed int, unsigned int or plain int. Compilers may allow other integer types (GCC accepts unsigned char, uint8_t and friends) as an extension, and C23 adds _BitInt(N) types. For portable code, stick to unsigned int, signed int and bool.
  • The width must be a constant from 0 up to the number of bits in the type. unsigned x : 33; is an error where unsigned has 32 bits.
  • You can mix bit-fields and normal members in the same struct.

Flags in one word

The most common use is a set of on/off options. A 1-bit bool or unsigned field reads naturally:

C Permission flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Seven bits of information share one storage unit. The struct is still 4 bytes because the unsigned field gives the whole struct the size and alignment of an unsigned int; a struct with only the four bool : 1 fields is 1 byte on GCC. Members you leave out of the initializer are zero, exactly like normal struct members.

Compare this with the flag-with-masks style from Enumerations and Bitwise Operators:

Bit-fields Masks on an unsigned
Set one option p.can_write = true; flags |= PERM_WRITE;
Test one option if (p.can_write) if (flags & PERM_WRITE)
Test several at once one test per field if ((flags & mask) == mask)
Pass to a function the whole struct one integer
Exact bit positions up to the compiler you decide

Bit-fields are more readable for named options. Masks win when you need to combine, compare or store the whole set as one number, or when the exact bit positions matter.

Range, overflow and signedness

A bit-field holds only as many values as its width allows. An unsigned field of width n holds 0 to 2n โˆ’ 1, and values that don't fit wrap around (they're reduced modulo 2n, just like any unsigned conversion):

C Wrapping and signed bit-fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The counter goes 0 to 7 and starts again at 0. Storing 12 keeps only the low 3 bits (1100 โ†’ 100), giving 4. When you assign a constant that obviously doesn't fit, such as c.small = 12;, GCC warns: unsigned conversion from 'int' to 'unsigned char:3' changes value from '12' to '4' [-Woverflow]. With a variable, as here, there's no warning, so check ranges yourself when values come from outside.

The signed field uses two's complement in 3 bits, so it holds -4 to 3. Storing a value outside that range in a signed bit-field gives an implementation-defined result (GCC wraps it), so don't rely on it.

Warning: Never declare a bit-field as plain int when the sign matters. For bit-fields only, the standard lets the compiler decide whether plain int means signed int or unsigned int. GCC treats it as signed, so int flag : 1; can hold only 0 and -1, and flag = 1; then reads back as -1. Write unsigned or bool for flags, and signed when you really want negatives.

What you can't do with bit-fields

A bit-field doesn't start at a byte address, so a few normal operations are forbidden:

C
struct packed_date d;
unsigned *p = &d.day;           /* error: cannot take address of bit-field 'day' */
size_t n = sizeof d.day;        /* error: 'sizeof' applied to a bit-field */
scanf("%u", &d.day);            /* error for the same reason as & */

To read a bit-field from input, read into a normal variable, check its range, then assign it. Also, you can't make arrays of bit-fields; use an array of structs that contain bit-fields, or a bit array built with masks.

Unnamed and zero-width bit-fields

Two special forms control the layout:

  • An unnamed bit-field like unsigned : 3; reserves 3 bits of padding. You can't access it; it just keeps space, for example to mirror a reserved area.
  • An unnamed bit-field of width 0, unsigned : 0;, says "start the next bit-field in a fresh storage unit".
C Viewing the layout on GCC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

memset clears every byte first, so the reserved bits are known to be zero. Then memcpy copies the struct's bytes into two uint32_t values, so you can look at the bits (see Unions for why memcpy is the safe way to reinterpret bytes). On GCC for x86-64, the first field lands in the lowest bit: ready is bit 0, error bit 1, two reserved bits, then mode = 101 in bits 4โ€“6. The zero-width field pushes counter into the second 32-bit unit, which is why the struct is 8 bytes instead of 4.

Another compiler, or the same compiler on a big-endian machine, may order the bits differently. That's the core portability problem, covered next.

Portability limits

The C standard leaves most layout decisions to the implementation:

  • Bit order. Whether the first field occupies the high or low bits of its unit.
  • Storage unit size. Which unit the compiler uses and whether a field that doesn't fit in the remaining bits straddles into the next unit or starts a new one.
  • Alignment and padding of the whole struct (more in Padding and Alignment).
  • Plain int signedness, as warned above.
  • Atomicity. Writing one bit-field reads and rewrites the whole unit, so two threads updating neighboring bit-fields of one struct can clobber each other (a data race in C11 terms; see Multithreading).

So bit-fields are a good fit for in-memory data: compact records, option sets, game state. They are a poor fit for external formats with a fixed bit layout: network packet headers, file headers, hardware registers, anything another program or compiler must read. For those, use a fixed-width integer (uint16_t, uint32_t) with explicit shifts and masks:

C Portable packing with shifts and masks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The result is the same on every compiler and every machine, because you chose every bit position. It's more code, but it's the only reliable way to match a published format. Many projects use bit-fields for internal structures and explicit masks at the boundary where data is read or written.

When to use bit-fields

Use them when:

  • You store many records and memory matters (a million 4-byte structs instead of 12-byte ones saves 8 MB).
  • You want readable named flags inside one program.
  • The exact bit positions don't matter to anyone outside your program.

Avoid them when:

  • The data is saved to a binary file or sent over a network.
  • Several threads update fields of the same struct.
  • You need the address of a member or want to read it directly with scanf.
  • Speed matters more than size: every access to a bit-field costs extra shift and mask instructions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A struct has unsigned hour : 5;. Which range of values can the field hold?

    An unsigned bit-field of width 5 holds 0 to 2^5 - 1, which is 0 to 31. That's enough for the hours of a day.
  2. 2. c.small is unsigned small : 3;. After int v = 13; c.small = v;, what does c.small contain?

    Only the low 3 bits are kept, so 13 (binary 1101) becomes 101, which is 5. Unsigned bit-fields wrap modulo 2^width.
  3. 3. Which of these is NOT allowed with a bit-field member?

    A bit-field usually doesn't start at a byte address, so & (and therefore scanf into it) and sizeof on it are compile errors.
  4. 4. Why is int flag : 1; a bad way to declare a flag?

    For bit-fields, the compiler decides whether plain int is signed. On GCC it is, so a 1-bit int field holds 0 and -1 and flag = 1 reads back as -1. Use unsigned or bool.
  5. 5. You need to build a 16-bit network header with fields at exact bit positions. What's the most portable approach?

    Bit order and storage units of bit-fields are implementation-defined. Shifts and masks on a fixed-width integer put every bit exactly where you say on every compiler.

Summary

  • A bit-field is a struct member with a width: unsigned month : 4;. Neighboring bit-fields share storage units.
  • Use unsigned int, signed int or bool; plain int has implementation-defined signedness in bit-fields.
  • Unsigned bit-fields wrap modulo 2width; GCC warns (-Woverflow) only for constants that don't fit.
  • You can't take a bit-field's address, apply sizeof to it, or make arrays of them.
  • unsigned : n; reserves bits; unsigned : 0; starts a new storage unit.
  • Bit order, straddling and unit size are implementation-defined: use bit-fields for in-memory data and explicit shifts and masks for external formats.

Next: Padding and Alignment