Course contentsShow
← C
Lesson 648 of 1,2199. Structures and UnionsFree lesson

The colon operator and bit width

The colon operator and bit width

What you'll learn: How to use the colon operator inside a structure to pack multiple pieces of data into a single byte.

Thinking in Bits, Not Bytes

Normally, the smallest variable you can create in C is a char, which occupies 8 bits. However, sometimes you need to store values that are much smaller. Imagine you are building a controller for a smart home. You need to store whether a light is ON or OFF (1 bit) and the current day of the week (1 to 7, which fits in 3 bits).

If you use standard int variables for these, you would waste 64 bits of memory to store only 4 bits of actual information. In systems with very limited memory, like an embedded chip in a microwave or a digital watch, this waste adds up quickly.

The Colon Syntax

C allows you to specify exactly how many bits a structure member should occupy using a bit-field. You do this by placing a colon (:) after the variable name, followed by the number of bits.

struct DeviceStatus {
    unsigned int isOn : 1;      // Uses only 1 bit (0 or 1)
    unsigned int dayOfWeek : 3; // Uses 3 bits (0 to 7)
    unsigned int brightness : 4; // Uses 4 bits (0 to 15)
};

In this example, the entire struct can fit into a single 8-bit byte. The colon tells the compiler: "Don't give isOn a full integer's worth of space; just give it one solitary bit."

How it Works

When you use the colon operator, the compiler packs these fields side-by-side in memory. It handles all the complex math of shifting bits around behind the scenes. You can treat status.dayOfWeek just like a normal variable in your code, but if you try to assign the number 10 to it, it will overflow because 10 (binary 1010) requires 4 bits, and you only allocated 3.

This is the ultimate tool for "data tetris," allowing you to squeeze maximum functionality out of every byte of RAM.

Key takeaway

The colon operator defines the "bit width" of a structure member, allowing you to store small integers in a specific number of bits to save memory.