Loading...

C essentialsAdvanced Topics

Bitwise operations, bit manipulation & bit-fields

12 min lesson

Next
  • Bitwise operations work directly on the individual bits of integers, using operators like &, |, ^, ~, << and >>.
  • They matter because some problems need tight control of bits: flags, permissions, low-level protocols, graphics and embedded systems.
  • Think of an integer as a row of light switches. Bitwise operators let you turn specific switches on, off, or check their state without touching the others.
  • & (AND) keeps a bit only if both sides have 1, useful for masking.
  • | (OR) sets a bit if either side has 1, useful for turning flags on.
  • ^ (XOR) flips a bit when the two sides differ, useful for toggling.
  • ~ (NOT) flips every bit, << shifts left (multiplies by powers of two), and >> shifts right (divides by powers of two for unsigned values).
  • The computer works on bits in the CPU's registers; these operations are extremely fast, often one instruction.
  • The syntax is: flags |= MASK; to set, flags &= ~MASK; to clear, and if (flags & MASK) to test.
  • A realistic use: storing user permissions (read, write, execute) in one integer, or packing several small values into a single word.
  • A surprising detail: shifting a signed negative value right is implementation-defined; use unsigned types for shift-based math.
  • The example program uses bit flags to represent read, write and execute permissions, then tests, sets and clears them with bitwise operators.
Keep in mind
  • Use unsigned types for bit manipulation to avoid surprises with shifts and sign bits.
  • Set bits with |=, clear with &= ~, toggle with ^=, and test with &.
  • Name masks with clear constants so the code reads well.
  • Use bit-fields only when you really need to save space; they have portability quirks.
  • Bit-level control is powerful. You are thinking at a deeper level now!
main.c
#include <stdio.h>

// Each permission is one bit; combined with OR
typedef enum {
    PERM_READ    = 1u << 0,
    PERM_WRITE   = 1u << 1,
    PERM_EXECUTE = 1u << 2
} Perm;

int main(void) {
    // Start with read and write permissions
    unsigned int flags = PERM_READ | PERM_WRITE;

    // Test whether the read bit is set
    printf("Read?    %u\n", (flags & PERM_READ) != 0);
    // Test whether the execute bit is set
    printf("Execute? %u\n", (flags & PERM_EXECUTE) != 0);

    // Turn on the execute bit with OR
    flags |= PERM_EXECUTE;
    // Turn off the write bit by ANDing with the inverse mask
    flags &= ~PERM_WRITE;

    // Print the final flags as a number and check each bit
    printf("Flags: %u\n", flags);
    printf("Read?    %u\n", (flags & PERM_READ) != 0);
    printf("Write?   %u\n", (flags & PERM_WRITE) != 0);
    printf("Execute? %u\n", (flags & PERM_EXECUTE) != 0);

    return 0;
}

What happens: Read? 1 Execute? 0 Flags: 5 Read? 1 Write? 0 Execute? 1

Breaking it down

Bit masks

1u << 0, 1u << 1, 1u << 2

Each expression puts a 1 in a different bit position, giving masks for read, write and execute.

Combining flags

PERM_READ | PERM_WRITE

OR sets both bits, giving a value with read and write enabled.

Testing a bit

(flags & PERM_READ) != 0

AND keeps only the read bit; if it is nonzero, the bit is set. The != 0 makes the result clearly a boolean.

Setting a bit

flags |= PERM_EXECUTE;

OR with the mask turns the execute bit on without changing the others.

Clearing a bit

flags &= ~PERM_WRITE;

AND with the inverted mask turns the write bit off and leaves the other bits untouched.

Bitwise operators

OperatorNameEffectExample
&ANDKeep bit if both 1flags & MASK
|ORSet bit if either 1flags | MASK
^XORFlip bit if differentflags ^ MASK
~NOTFlip all bits~MASK
<<Left shiftMultiply by 2^n1u << 3
>>Right shiftDivide by 2^n16u >> 2

A helpful analogy

An integer is like a row of light switches. Bitwise operators let you work on specific switches without disturbing the others. AND checks whether a switch is on, OR turns a switch on, clearing turns it off, and XOR flips it.

Nesting rules

  • 1.Use unsigned types for bit manipulation to avoid sign-related surprises.
  • 2.Set bits with |=, clear with &= ~, toggle with ^=, and test with &.
  • 3.Parenthesize expressions like (flags & MASK) before comparing to 0.
  • 4.Do not shift by a negative amount or by more than the width of the type; both are undefined behavior.

Common mistakes

Using == to test a bit

Avoid

if (flags == PERM_READ) // wrong

Use instead

if ((flags & PERM_READ) != 0)

== compares the whole value. If several bits are set, the comparison fails even when the read bit is on. Use & with a mask.

Clearing with &= MASK instead of &= ~MASK

Avoid

flags &= PERM_WRITE; // clears all but write

Use instead

flags &= ~PERM_WRITE;

AND with the mask keeps only the masked bits. AND with the inverted mask keeps everything except that bit.

Shifting a signed value right

Avoid

int x = -8; x >> 1; // implementation-defined

Use instead

unsigned int x = 8u; x >> 1;

Right-shifting a negative signed value is implementation-defined. Use unsigned types for predictable shifts.

Quick tips

  • •Define masks with 1u << n so they are unsigned and readable.
  • •Print flags in binary by writing a small helper; it makes bit logic obvious.
  • •Use bit-fields in structs only for compact storage; they depend on compiler layout.
  • •Try toggling a bit with ^= to see it flip between 0 and 1.
  • •Use -fsanitize=undefined to catch bad shifts during testing.
Previous
Next