Course contentsShow
← Computer Science
Lesson 163 of 2,8724. Introduction to ProgrammingFree lesson

Bitwise Operators

Performing bit-level operations with AND, OR, XOR, NOT, and bit shift operators.

Bitwise Operators

You'll learn how to manipulate individual bits in binary numbers using specialized operators that work at the lowest level of data.

What Are Bitwise Operators?

Bitwise operators work directly on the binary representation of integers, performing operations on each bit position independently. While arithmetic operators like + or * treat numbers as whole values, bitwise operators let you examine and modify the individual 0s and 1s that make up those numbers in memory.

The Core Operators

AND (&): Returns 1 only if both bits are 1. Think of it like an "all or nothing" filter.

  • 5 & 3 → 101 & 011 → 001 → 1

OR (|): Returns 1 if at least one bit is 1. It's like combining switches.

  • 5 | 3 → 101 | 011 → 111 → 7

XOR (^): Returns 1 if bits are different. Great for detecting changes.

  • 5 ^ 3 → 101 ^ 011 → 110 → 6

NOT (~): Flips every bit (0 becomes 1, 1 becomes 0). This inverts the pattern.

  • ~5 → ~00000101 → 11111010 (result depends on integer size)

Left Shift (<<): Moves all bits left, filling with 0s. Each shift multiplies by 2.

  • 5 << 1 → 101 becomes 1010 → 10

Right Shift (>>): Moves all bits right, discarding rightmost bits. Each shift divides by 2.

  • 5 >> 1 → 101 becomes 10 → 2

Why It Matters

Bitwise operations are lightning-fast and essential for low-level programming, graphics, cryptography, and optimizing memory usage with flags.

Key Takeaway: Bitwise operators manipulate individual bits in binary numbers, enabling efficient low-level data operations like masking, toggling, and shifting.