C++ Bitwise Operators

🧮 C++ Bitwise Operators – Work with Bits Like a Pro

Bitwise operators let you perform operations directly on bits – the 1s and 0s that make up all data! ⚙️ They’re super powerful when you want speed and control. Let’s flip some bits! 🔀

📋 List of Bitwise Operators

  • & – AND
  • | – OR
  • ^ – XOR (exclusive OR)
  • ~ – NOT (one’s complement)
  • << – Left shift
  • >> – Right shift

🔧 Example: Bitwise in Action

#include <iostream>
using namespace std;

int main() {
    int a = 5;    // 0101 in binary
    int b = 3;    // 0011 in binary

    cout << "a & b: " << (a & b) << endl;   // 0001 = 1
    cout << "a | b: " << (a | b) << endl;   // 0111 = 7
    cout << "a ^ b: " << (a ^ b) << endl;   // 0110 = 6
    cout << "~a: " << (~a) << endl;        // Inverts bits
    cout << "a << 1: " << (a << 1) << endl; // Left shift (x2)
    cout << "a >> 1: " << (a >> 1) << endl; // Right shift (/2)

    return 0;
}

Try It Now

🧠 Bitwise Thinking?

Bitwise operations are often used in:

  • Performance-critical applications
  • Low-level device programming
  • Game engines and graphics
  • Flags and binary data structures

Once you get used to them, you’ll feel like a binary wizard! 🧙‍♂️