Course contentsShow
← C
Lesson 182 of 1,2193. Operators and ExpressionsFree lesson

Setting bits with `|`

Setting bits with |

What you'll learn: How to use the Bitwise OR operator to turn specific bits "on" without changing the rest of your data.

In C programming, we often need to flip a specific switch inside a byte. Imagine a row of eight light switches on a wall. If you want to make sure the third switch is "on," you don't want to fumble around in the dark and accidentally flip the others. The Bitwise OR operator (|) acts like a master key that only affects the switches you choose.

The Logic of OR

The | operator compares two numbers bit by bit. For every position, it asks: "Is at least one of these bits a 1?" If the answer is yes, the resulting bit is a 1. If both are 0, the result is 0.

  • 0 | 0 = 0
  • 0 | 1 = 1
  • 1 | 0 = 1
  • 1 | 1 = 1

Because 1 | anything is always 1, we use this operator to "set" bits (turn them to 1).

Using a "Bitmask"

To set a specific bit, we use a "mask." A mask is a number where only the bit you want to change is set to 1, and everything else is 0.

Think of it like a stencil you use when spray-painting. The holes in the stencil (the 1s) let the paint through to the wall, while the solid cardboard (the 0s) protects the existing paint underneath. When you OR a variable with a mask, the 0s in your mask leave the original bits alone, while the 1s force the target bits to turn on.

Code Example: Activating a Feature

Suppose you are writing software for a car. You have a variable called dashboard_lights where each bit represents a different light.

#include <stdio.h>

int main() {
    // Binary: 00000000 (All lights off)
    unsigned char dashboard_lights = 0; 

    // We want to turn on the "Check Engine" light, which we've 
    // decided is the 3rd bit from the right (value of 4).
    // Mask in binary: 00000100
    unsigned char check_engine_mask = 4;

    // Use OR to set the bit
    dashboard_lights = dashboard_lights | check_engine_mask;

    // dashboard_lights is now 4 (Binary: 00000100)
    printf("Dashboard status: %d\n", dashboard_lights);

    return 0;
}

By using |, you ensure the "Check Engine" light is on. If it was already on, the OR operation wouldn't change anything—it simply guarantees that bit is now a 1.

Key takeaway

Use the | operator with a bitmask to force specific bits to 1 while keeping all other bits exactly as they were.