DEV Community

Anurag Parmar
Anurag Parmar

Posted on

Day 2 of C++ Programming: Bitwise Operators (AND, Shift, NOT)

On Day 2 of my C++ journey, I explored bitwise operators.

These are super powerful because they operate directly on binary bits — the true language of the computer.

At first, they look abstract, but once I saw the outputs of small numbers, I understood why they’re so important.


✅ Example 1: Bitwise AND (&)


cpp
#include <iostream>
using namespace std;

int main() {
    int x = 11, y = 7, z;
    z = x & y; 
    cout << z << endl;
    return 0;
}
Explanation
11 → 1011 (binary)
7 → 0111 (binary)
1011 & 0111 → 0011 = 3
👉 AND is useful in masking operations (filtering specific bits).

✅ Example 2: Bitwise Shift (<<)
C++

#include <iostream>
using namespace std;

int main() {
    char x = 5, y;
    y = x << 1; // left shift by 1
    cout << (int)y << endl;
    return 0;
}
Explanation
5 → 0101 (binary)
Shift left by 1 → 1010 (binary) = 10
👉 Shifting left is basically multiplying by 2.
✅ Example 3: Bitwise NOT (~)
C++

#include <iostream>
using namespace std;

int main() {
    char x = 5, y;
    y = ~x;
    cout << (int)y << endl;
    return 0;
}
Explanation
5 → 00000101 (binary)
~x flips all bits → 11111010
Result = -6 (in signed integer representation).

Enter fullscreen mode Exit fullscreen mode

Top comments (0)