Bit Manipulation
Understanding Bitwise Operations in C Programming
Introduction to Bit Manipulation (बिट मैनिपुलेशन का परिचय)
Bit manipulation binary numbers के individual bits के साथ operations करने का process है। ये low-level programming में बहुत important है।
Bit manipulation is the process of performing operations on individual bits of binary numbers. It is very important in low-level programming.
Key Points (मुख्य बिंदु):
- Bit manipulation memory और performance को optimize करता है
- Bit manipulation optimizes memory and performance
- Bitwise operators individual bits पर operate करते हैं
- Bitwise operators operate on individual bits
- Bit manipulation hardware operations में useful है
- Bit manipulation is useful in hardware operations
1
0
1
0
1
0
1
0
Bitwise Operators (बिटवाइज ऑपरेटर्स)
Bitwise operators और उनका use:
Bitwise operators and their usage:
// Bitwise AND
int a = 5; // 0101
int b = 3; // 0011
int c = a & b; // 0001 (1)
// Bitwise OR
int d = a | b; // 0111 (7)
// Bitwise XOR
int e = a ^ b; // 0110 (6)
// Bitwise NOT
int f = ~a; // 1010 (-6)
// Left Shift
int g = a << 1; // 1010 (10)
// Right Shift
int h = a >> 1; // 0010 (2)
Operator (ऑपरेटर) | Description (विवरण) |
---|---|
& | Bitwise AND |
& | Bitwise AND |
| | Bitwise OR |
| | Bitwise OR |
^ | Bitwise XOR |
^ | Bitwise XOR |
~ | Bitwise NOT |
~ | Bitwise NOT |
<< | Left Shift |
<< | Left Shift |
>> | Right Shift |
>> | Right Shift |
Bit Fields (बिट फील्ड्स)
Bit fields और उनका use:
Bit fields and their usage:
// Bit field structure
struct {
unsigned int flag1 : 1; // 1 bit
unsigned int flag2 : 1; // 1 bit
unsigned int value : 4; // 4 bits
unsigned int : 2; // 2 unused bits
} status;
// Using bit fields
status.flag1 = 1;
status.flag2 = 0;
status.value = 5;
// Checking flags
if (status.flag1) {
printf("Flag1 is set\n");
}
Bit Field Features (बिट फील्ड फीचर्स):
- Memory efficient storage
- Memory efficient storage
- Direct bit access
- Direct bit access
- Hardware register mapping
- Hardware register mapping
Common Operations (कॉमन ऑपरेशन्स)
Common bit manipulation operations:
Common bit manipulation operations:
// Set a bit
void set_bit(int *num, int pos) {
*num |= (1 << pos);
}
// Clear a bit
void clear_bit(int *num, int pos) {
*num &= ~(1 << pos);
}
// Toggle a bit
void toggle_bit(int *num, int pos) {
*num ^= (1 << pos);
}
// Check if bit is set
int is_bit_set(int num, int pos) {
return (num & (1 << pos)) != 0;
}
// Count set bits
int count_set_bits(int num) {
int count = 0;
while (num) {
count += num & 1;
num >>= 1;
}
return count;
}
Best Practices (सर्वोत्तम प्रथाएं)
Bit manipulation के best practices:
Best practices for bit manipulation: