Topic 25 of 100 Operators in C Interactive Tutorial

Bitwise Operations in C: AND, OR, XOR, Shift, and Complement

14 mins read Last updated: 22 Aug 2026 27,300 views
C Compiler 0.00%

What is Bitwise Operations in C? Core Concept & Direct Summary

Core Objective & Problem Statement

How do bitwise operators (`&`, `|`, `^`, `~`, `<<`, `>>`) manipulate individual bits directly in memory?

Direct Answer Summary

Every number in your computer is secretly a row of tiny switches. The number 5? That's0101— four switches: off, on, off, on. The number 255? Eight switches, all on.

Most programming languages never let you touch those switches. C hands you the control panel.

Bitwise operatorswork directly on the individual bits of your data — flipping them, comparing them, sliding them left and right. This is the closest you can get to hardware without writing assembly, and it's why C dominates embedded systems, device drivers, and anywhere performance is measured in nanoseconds.

Fair warning: this is the topic that makes beginners' eyes glaze over. But stick with me — because once youseethe bits, a whole category of clever programming tricks becomes obvious. Let's flip some switches.

How Does Bitwise Operations in C Work? In-Depth Mechanics & Architecture

Quick Refresher: Numbers as Bits

Before the operators, thirty seconds on binary. Every integer is stored as bits — 1s and 0s:

main.c
Run Online
Decimal 5 = 0 1 0 1(4+1)Decimal 3 = 0 0 1 1(2+1)Decimal 10 = 1 0 1 0(8+2)

Each position is a power of two (8, 4, 2, 1 reading left to right). That's all binary is: switches adding up. Now — the operators that manipulate them.

The Six Bitwise Operators

OperatorNameOne-Line Meaning
&ANDBit stays 1 only ifbothbits are 1
|ORBit is 1 ifeitherbit is 1
^XORBit is 1 if bits aredifferent
~NOT (complement)Flipsevery single bit
<<Left shiftSlides bitsleft(×2 per step)
>>Right shiftSlides bitsright(÷2 per step)

The key difference from logical operators: logical operators treat values as whole truths;bitwise operators compare bit by bit, position by position.

& — Bitwise AND: The Shared-Bit Finder

&compares each pair of bits and keeps 1 only wherebothare 1:

main.c
Run Online
5 = 0 1 0 1 3 = 0 0 1 1 -------- AND 0 0 0 1 = 1
main.c
Run Online
int a = 5, b = 3;
printf("%d\n", a & b);
// 1 — only the last bit matched

The classic use — testing whether a bit is ON:

main.c
Run Online
int flags = 5;
// 0101 — bits 0 and 2 are setif (flags & 1) {
// test bit 0 (mask: 0001)    printf("Bit 0 is ON\n");   // runs — 0101 & 0001 = 0001
}

This pattern —value & mask— is how embedded programmers check hardware status bits:is the sensor flag set? Is the device ready bit on?

| — Bitwise OR: The Bit Setter

|keeps 1 wherevereitherbit is 1:

main.c
Run Online
5 = 0 1 0 1 3 = 0 0 1 1 -------- OR 0 1 1 1 = 7

The classic use — turning a bit ON without disturbing others:

main.c
Run Online
int flags = 5;
// 0101flags = flags | 2;
// set bit 1 (mask: 0010)printf("%d\n", flags);
// 7 (0111) — bit 1 now ON, others untouched

This is how yousetflags: OR with a mask that has 1 exactly where you want to switch on. File permissions, hardware registers, game state flags — all use this.

^ — Bitwise XOR: The Difference Detector

^keeps 1 only where bitsdiffer:

main.c
Run Online
5 = 0 1 0 1 3 = 0 0 1 1 -------- XOR 0 1 1 0 = 6

XOR has two magical properties that power famous tricks:

main.c
Run Online
x ^ x // always 0 — anything XOR itself cancels outx ^ 0    // always x — XOR with zero changes nothing

The classic party trick — swapping without a temporary variable:

main.c
Run Online
int x = 5, y = 9;
x = x ^ y;
y = x ^ y;
x = x ^ y;
printf("x=%d, y=%d\n", x, y);
// x=9, y=5 — swapped!

(It's a great interview demo, though in real code the temporary-variable version is clearer and equally fast.)

~ — Bitwise NOT: The Bit Flipper

~is unary — it flipseverybit, 1→0 and 0→1:

main.c
Run Online
int a = 5;
// 0000...0101printf("%d\n", ~a);
// -6 ?!

Wait — negative six?Welcome to two's complement: computers store negative numbers by flipping all bits and adding 1. The math works out to a tidy rule:

So~5is-6,~0is-1, and~(-3)is2. Confusing at first sight, perfectly logical underneath.

<< — Left Shift: The Doubling Machine

<<slides all bits left, filling the right side with zeros:

main.c
Run Online
5 << 1: 0101 → 1010 = 10(doubled!)
5 << 2: 0101 → 10100 = 20(doubled again!)
main.c
Run Online
int a = 5;
printf("%d\n", a << 1);
// 10
printf("%d\n", a << 2);
// 20

The rule:x << nmultiplies x by 2ⁿ.1 << 3is 8.3 << 2is 12. Shifting left is a lightning-fast multiplication trick — and it's also how youbuildbit masks:

main.c
Run Online
int mask = 1 << 3;
// 0000...1000 — a mask targeting bit 3

>> — Right Shift: The Halving Machine

>>slides bits right, discarding what falls off:

main.c
Run Online
20 >> 1: 10100 → 01010 = 10(halved!)
20 >> 2: 10100 → 00101 = 5(halved again!)
main.c
Run Online
printf("%d\n", 20 >> 1);
// 10
printf("%d\n", 20 >> 2);
// 5

The rule:x >> ndivides x by 2ⁿ (integer division). Bit 0 falling off is how you know the number was odd.

Real-World Power: Flag Management

Here's where it all pays off — packing multiple yes/no settings into a single integer:

main.c
Run Online
#include <stdio.h>
// each setting gets its own bit
#define BOLD(1 << 0) // 0001 = 1
#define ITALIC(1 << 1) // 0010 = 2
#define UNDERLINE(1 << 2) // 0100 = 4
#define STRIKE(1 << 3) // 1000 = 8
int main() {
    int style = 0;
    // nothing on
    style = style | BOLD;
    // turn bold ON
    style = style | UNDERLINE;
    // turn underline ON
    printf("Style flags: %d\n", style);
    // 5 (0101)
    if (style & BOLD) {
        printf("Text is bold\n");
        // runs
    }
    if (!(style & ITALIC)) {
        printf("Text is NOT italic\n");
        // runs
    }
    style = style & ~UNDERLINE;
    // turn underline OFF (AND with flipped mask)
    printf("After removing underline: %d\n", style);
    // 1
    style = style ^ BOLD;
    // TOGGLE bold with XOR
    printf("After toggling bold: %d\n", style);
    // 0
    return 0;
}

Four patterns, memorized by every systems programmer:

GoalPatternExample
Seta bitflags | MASKstyle | BOLD
Cleara bitflags & ~MASKstyle & ~UNDERLINE
Togglea bitflags ^ MASKstyle ^ BOLD
Checka bitflags & MASKstyle & BOLD

One integer now carries 32 independent on/off switches. This is how device drivers, file permissions, and game engines pack state — and it works on the tiniest microcontrollers.

⚠️ Bitwise vs Logical: The Critical Distinction

One last warning, because this confusion causes real bugs:

main.c
Run Online
printf("%d\n", 4 & 2);
// 0 — bitwise: no shared bits (0100 & 0010)
printf("%d\n", 4 && 2);
// 1 — logical: both non-zero → true
  • &,|,^workbit by bit— results can be any number
  • &&,||,!work onwhole values as truths— results are only 0 or 1

Use logical operators forconditions, bitwise operators forbits. Never mix the rooms.

Runnable C Code Example & Practical Implementation

main.c
Run Online
#include <stdio.h>
int main() {
    unsigned char flags = 0b00000100;
    // Bit 2 set
    // Set bit 0
    flags |=(1 << 0);
    printf("Flags after setting bit 0: 0x%02X\
", flags);
    // Check bit 2
    if (flags &(1 << 2)) {
        printf("Bit 2 is active!\
");
    }
    // Toggle bit 2
    flags ^=(1 << 2);
    printf("Flags after toggling bit 2: 0x%02X\
", flags);
    return 0;
}

Key Takeaways, Best Practices & Memory Safety Rules

Best Practice & Key Takeaways
Always use unsigned integer types (uint8_t, uint32_t) when performing bitwise shift and mask operations to avoid sign-extension undefined behavior.

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked C programming interview questions
Q

Q: How do you swap two integer variables without using a temporary variable?

A: Using XOR: `a ^= b; b ^= a; a ^= b;`
Q

Q: What is the difference between bitwise `&` and logical `&&`?

A: `&` performs bit-by-bit conjunction on all bits of its operands, whereas `&&` treats operands as holistic boolean truth values and supports short-circuiting.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations