Bit Manipulation
C mein 6 bitwise operators hain: & (AND — dono bits 1 hon to 1), | (OR — koi ek bit 1 ho to 1), ^ (XOR — bits alag hon to 1), ~ (NOT — sab bits flip), << (left shift — bits ko left move karo, jaise ×2), >> (right shift — bits ko right move karo, jaise ÷2).
Real-world use: flags/permissions ko ek hi integer mein pack karna (jaise Unix file permissions), fast multiplication/division by powers of 2, aur memory-critical embedded systems mein individual bits control karna (jaise hardware registers).
Common tricks: n & 1 batata hai number odd hai ya even (last bit check). n << 1 number ko double kar deta hai. n & (n-1) ek popular trick hai jo lowest set bit ko clear kar deti hai — power-of-2 check karne mein use hoti hai.
int a = 5; // binary: 0101
int b = 3; // binary: 0011
printf("%d\n", a & b); // 0001 = 1 (AND)
printf("%d\n", a | b); // 0111 = 7 (OR)
printf("%d\n", a ^ b); // 0110 = 6 (XOR)
printf("%d\n", a << 1); // 1010 = 10 (left shift = ×2)
printf("%d\n", a >> 1); // 0010 = 2 (right shift = ÷2)
// Odd/even check:
if (a & 1) printf("Odd\n"); else printf("Even\n"); // Odd
// Power of 2 check:
int isPowerOf2 = a && !(a & (a - 1));- & | ^ ~ << >> = 6 bitwise operators
- n & 1 = odd/even check, n << 1 = ×2, n >> 1 = ÷2
- Flags/permissions pack karne aur embedded systems mein bahut use hote hain
Bahut common bit-manipulation pattern hai kisi specific bit (position n) ko set (1 karna), clear (0 karna), ya toggle (flip karna) karna — flags, permissions, ya hardware registers manipulate karte waqt bahut use hota hai.
int num = 0b1010; // binary literal (C23) ya 10 decimal
// Bit 0 (rightmost) set karo:
num = num | (1 << 0); // 1011 = 11
// Bit 1 clear karo:
num = num & ~(1 << 1); // AND with inverted mask
// Bit 2 toggle karo:
num = num ^ (1 << 2); // XOR flips the bit
// Bit n check karo (set hai ya nahi):
int isSet = (num >> 3) & 1;Ek number mein kitne bits "1" hain ye count karna ("population count" / "hamming weight") ek classic interview problem hai — Brian Kernighan's algorithm ek elegant trick use karta hai: n & (n-1) har baar lowest set bit clear karta hai, jab tak n zero na ho jaaye.
int countSetBits(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1); // lowest set bit clear karo
count++;
}
return count;
}
int main() {
printf("%d\n", countSetBits(7)); // 111 -> 3 bits set
printf("%d\n", countSetBits(8)); // 1000 -> 1 bit set
return 0;
}