🔴 Advanced  ·  Lesson 43

Bitwise Operations

Bitwise Operations

Bitwise Operators

Bitwise operators work at the binary bit level. They are used in low-level programming, flags, masks and performance-sensitive code.

Operators

OperatorNameExample
&AND1 & 1 = 1
|OR1 | 0 = 1
^XOR1 ^ 1 = 0
~NOTFlips bits
<<Left Shiftx << 1 means x*2
>>Right Shiftx >> 1 means x/2

Examples

C Language
#include <stdio.h>

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

    printf("a & b = %d\n", a & b);
    printf("a | b = %d\n", a | b);
    printf("a ^ b = %d\n", a ^ b);
    printf("a << 1 = %d\n", a << 1);
    printf("a >> 1 = %d", a >> 1);
    return 0;
}
a & b = 1 a | b = 7 a ^ b = 6 a << 1 = 10 a >> 1 = 2

Bit Tricks

C Language
// Check if nth bit is set
if(num & (1 << n)) printf("Set");

// Set nth bit
num = num | (1 << n);

// Clear nth bit
num = num & ~(1 << n);

// Toggle nth bit
num = num ^ (1 << n);

// Check even/odd
if(num & 1) printf("Odd"); else printf("Even");

Summary

  • Bitwise operators work on binary bits
  • AND, OR, XOR and NOT are common bit operators
  • Left shift often multiplies by powers of 2
  • Right shift often divides by powers of 2
  • Bit masks help check, set, clear and toggle bits

Bitwise Operators

Bitwise operators binary bits पर काम करते हैं। ये flags, masks और low-level programming में useful होते हैं।

Operators

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

Examples

C Language
int a = 5, b = 3;
printf("%d", a & b);  // 1
printf("%d", a | b);  // 7
printf("%d", a ^ b);  // 6

Bit Tricks

C Language
num & (1 << n);      // check nth bit
num | (1 << n);      // set nth bit
num & ~(1 << n);     // clear nth bit
num ^ (1 << n);      // toggle nth bit

सारांश

  • Bitwise operators binary level पर काम करते हैं
  • AND, OR, XOR, NOT common हैं
  • Left shift multiply जैसा काम कर सकता है
  • Right shift divide जैसा काम कर सकता है
  • Bit mask से bits check/set/clear कर सकते हैं
← Back to C Tutorial