Bitwise Operators
and Their Use-Cases



Understanding Bitwise Operators

Bitwise operators allow direct manipulation of individual bits of a number. These operators work at the binary level and are commonly used in low-level programming, performance optimizations, graphics, hardware control, and even simple algorithm tricks.

Why Bitwise?

Bitwise operations are extremely fast and can simplify complex operations. They're often used when memory or performance is critical.

Common Bitwise Operators

Example 1: Bitwise AND

Let’s take two numbers: 6 (which is 110 in binary) and 3 (011).

A = 6     // binary: 110
B = 3     // binary: 011
C = A & B // performs bitwise AND
print(C)

Output:

2

Explanation:

Bitwise AND compares each bit. Only if both bits are 1, the result is 1.

110
AND
011
=
010 → which is 2

Question:

What happens if we AND any number with 0?

Answer:

It always returns 0, because 0 AND anything is 0.

Example 2: Bitwise OR

A = 6     // binary: 110
B = 3     // binary: 011
C = A | B // performs bitwise OR
print(C)

Output:

7

Explanation:

110
OR
011
=
111 → which is 7

Example 3: Bitwise XOR

A = 6     // binary: 110
B = 3     // binary: 011
C = A ^ B // performs bitwise XOR
print(C)

Output:

5

Explanation:

XOR returns 1 only when the bits differ.

110
XOR
011
=
101 → which is 5

Example 4: Bitwise NOT

A = 6     // binary: 00000110
C = ~A    // flips all bits
print(C)

Output:

-7 (in two's complement systems)

Explanation:

Bitwise NOT inverts all bits. In two’s complement, ~6 becomes -7 because of how negative numbers are represented in binary.

Example 5: Left and Right Shift

A = 4      // binary: 100
B = A << 1 // shift left by 1 bit
C = A >> 1 // shift right by 1 bit
print(B)
print(C)

Output:

8
2

Explanation:

Left shift multiplies by 2, right shift divides by 2.

Real-World Use-Cases

Mini Exercise

Try this:

A = 10
print(A & 1) // What does this return?

Answer:

It returns 0, which means 10 is even (last bit is 0).

Summary

Bitwise operators are powerful tools that can optimize performance and simplify logic in many scenarios. Although they might seem complex initially, practicing with binary representations makes them intuitive over time.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M