Bitwise Operations in C

Bitwise Operations in C


Introduction

Bitwise operators in C are used to perform operations on individual bits of data.

👉 These operations are very fast and used in low-level programming.


What are Bitwise Operations?

Bitwise operations are:
👉 Operations performed on binary (bit-level) representation of numbers


Why Use Bitwise Operators?

  • ✔ Faster computations
  • ✔ Efficient memory usage
  • ✔ Used in system programming
  • ✔ Useful in flags and masks

Bitwise Operators

  • & → AND
  • | → OR
  • ^ → XOR
  • ~ → NOT
  • << → Left Shift
  • >> → Right Shift

1. Bitwise AND (&)

#include <stdio.h>

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

printf("%d", a & b);

return 0;
}

Output

1

👉 5 = 101
👉 3 = 011
👉 AND = 001 → 1


2. Bitwise OR (|)

#include <stdio.h>

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

printf("%d", a | b);

return 0;
}

Output

7

3. Bitwise XOR (^)

#include <stdio.h>

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

printf("%d", a ^ b);

return 0;
}

Output

6

4. Bitwise NOT (~)

#include <stdio.h>

int main() {
int a = 5;

printf("%d", ~a);

return 0;
}

Output

-6

5. Left Shift (<<)

#include <stdio.h>

int main() {
int a = 5;

printf("%d", a << 1);

return 0;
}

Output

10

6. Right Shift (>>)

#include <stdio.h>

int main() {
int a = 5;

printf("%d", a >> 1);

return 0;
}

Output

2

Bitwise Operators Table

Operator Operation Example
& AND a & b
| OR a | b
^ XOR a ^ b
~ NOT ~a
<< Left Shift a << 1
>> Right Shift a >> 1

Important Notes

  • Works on binary values
  • Faster than arithmetic operations
  • Used in low-level programming

Common Mistakes

  • ❌ Confusing logical and bitwise operators
  • ❌ Not understanding binary conversion
  • ❌ Using wrong operator

Pro Tips

  • ✔ Learn binary basics
  • ✔ Practice bitwise problems
  • ✔ Use for optimization
  • ✔ Useful in interviews

Conclusion

Bitwise operations are powerful tools in C programming. They allow fast and efficient manipulation of data at the bit level.

Master them for advanced programming skills.

👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.

Comments

Popular posts from this blog

Introduction to C Programming

Operators in C

Input & Output in C