CodeBlanks Logo Icon CodeBlanks

Bit fields

  • C course
  • Intermediate
  • Lesson 40/116
  • 5 min

Learn memory savings with bit fields.

Bit fields

Bit fields let you define struct members in bits rather than bytes. This is used for memory packing and flag management.

Example: struct Flags { unsigned a : 3; unsigned b : 1; };. Here a takes 3 bits, b takes 1 bit. a holds 0-7. The whole struct takes only 4 bits (half a byte); the compiler pads it to at least 1 byte. This is common in embedded systems, protocol headers and hardware registers. Bit fields save memory but require care for portability.

Bit field example

Bit fields are automatically masked when you assign a value. If you write 5 to unsigned a : 3;, 5 is stored; if you write 9, overflow happens and only the low 3 bits (1) are stored.

Example: struct Flags f; f.a = 5; f.b = 1;. Here f.a is 5 (binary 101), f.b is 1 (binary 1). If you write f.a = 9;, the low 3 bits of 9 are 1; so f.a becomes 1. This automatic masking is suitable for modeling hardware registers. Still, avoiding overflow values is a good habit for readability.

Practice Print flags with bit fields

Define struct Flags with unsigned a : 3; and unsigned b : 1;. In main, write struct Flags f;; assign f.a = 5; and f.b = 1;. Print with printf("%d %d\n", f.a, f.b);.

Starter code

main.c
#include <stdio.h>

// Define struct Flags (a 3 bits, b 1 bit)
// In main declare f, set a to 5, b to 1 and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

struct Flags {
    unsigned a : 3;
    unsigned b : 1;
};

int main(void) {
    struct Flags f;
    f.a = 5;
    f.b = 1;
    printf("%d %d\n", f.a, f.b);
    return 0;
}

Expected output

5 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the bit field expressions

Term Meaning
unsigned a : 3 3-bit field
unsigned b : 1 1-bit field
struct Flags Flag struct
: 3 Bit width

2 Complete the bit width

Question
struct Flags { unsigned a : ____; unsigned b : 1; };
Answer
struct Flags { unsigned a : 3; unsigned b : 1; };

Explanation: answer: 3. unsigned a : 3; defines a 3-bit field.

3 How many bits does unsigned a : 3; use?

  • 1
  • 3 Correct answer
  • 32
  • 0

Explanation: answer: 3. The : 3 suffix means 3 bits.

All lessons in Intermediate