C Bitwise Operators

C Bitwise Operators

Bitwise operators in C allow you to manipulate individual bits of integers. They are commonly used in:

✔ Low-level programming
✔ Embedded systems
✔ Network programming
✔ Performance-critical code
✔ Device drivers and microcontrollers

These operators work on data bit-by-bit.


🔹 List of Bitwise Operators

Operator Meaning Example
& Bitwise AND a & b
Bitwise OR
^ Bitwise XOR a ^ b
~ Bitwise NOT (complement) ~a
<< Left Shift a << n
>> Right Shift a >> n

⭐ Binary Example

Let:

a = 50101 (binary)
b = 30011 (binary)

1️⃣ Bitwise AND (&)

0101
0011
----

0001 → 1
#include <stdio.h>

int main() {
int a = 5, b = 3;
printf("%d", a & b);
return 0;
}


2️⃣ Bitwise OR (|)

0101
0011
----

0111 → 7
printf("%d", a | b);

3️⃣ Bitwise XOR (^)

XOR returns 1 when bits are different.

0101
0011
----

0110 → 6
printf("%d", a ^ b);

4️⃣ Bitwise NOT (~)

Flips all bits.

a = 5 0000 0101
~a 1111 1010 -6 (in signed representation: two’s complement)
printf("%d", ~a);

5️⃣ Left Shift (<<)

Shifts bits left, filling zeros.
Equivalent to multiplying by 2^n.

5 << 1 = 10
5 << 2 = 20
printf("%d", a << 1);
printf("\n%d", a << 2);

6️⃣ Right Shift (>>)

Shifts bits right.
Equivalent to dividing by 2^n.

5 >> 1 = 2
5 >> 2 = 1
printf("%d", a >> 1);


🧠 Practical Examples

✔ Checking if a Number is Even or Odd

(Using AND with 1)

#include <stdio.h>

int main() {
int num = 7;

if(num & 1)
printf("Odd");
else
printf("Even");

return 0;
}


✔ Swapping Two Variables Without a Temp

#include <stdio.h>

int main() {
int a = 5, b = 9;

a ^= b;
b ^= a;
a ^= b;

printf("a = %d, b = %d", a, b);
return 0;
}


✔ Turning a Specific Bit ON

int num = 8; // 1000
num = num | (1 << 1); // Turn ON 2nd bit

✔ Turning a Bit OFF

num = num & ~(1 << 1);

✔ Toggle a Bit

num = num ^ (1 << 1);


📌 Summary Table

Operation Example Result
AND 5 & 3 1
OR 5 3
XOR 5 ^ 3 6
NOT ~5 -6
Left shift 5 << 1 10
Right shift 5 >> 1 2

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *