What is the complete usage and practical application scenarios of bitwise operators in C language?
Bitwise Operators List:
-
Bitwise AND &
cunsigned int a = 0b10101010; // 170 unsigned int b = 0b11001100; // 204 unsigned int result = a & b; // 0b10001000 (136) -
Bitwise OR |
cunsigned int result = a | b; // 0b11101110 (238) -
Bitwise XOR ^
cunsigned int result = a ^ b; // 0b01100110 (102) -
Bitwise NOT ~
cunsigned int result = ~a; // 0b01010101 (85) -
Left Shift <<
cunsigned int result = a << 2; // 0b1010101000 (680) -
Right Shift >>
cunsigned int result = a >> 2; // 0b00101010 (42)
Practical Application Scenarios:
-
Bit Mask Operations
c#define FLAG_A 0x01 // 00000001 #define FLAG_B 0x02 // 00000010 #define FLAG_C 0x04 // 00000100 unsigned int flags = 0; // Set flag flags |= FLAG_A; flags |= FLAG_B; // Clear flag flags &= ~FLAG_A; // Check flag if (flags & FLAG_B) { printf("FLAG_B is set\n"); } // Toggle flag flags ^= FLAG_C; -
Bit Field Operations
cstruct BitField { unsigned int flag1 : 1; unsigned int flag2 : 1; unsigned int value : 6; }; -
Fast Calculations
c// Multiply by power of 2 int x = 5; int result = x << 3; // x * 8 = 40 // Divide by power of 2 int result = x >> 2; // x / 4 = 1 // Check odd/even if (x & 1) { printf("Odd\n"); } else { printf("Even\n"); } -
Data Compression
c// Pack two 8-bit values into 16-bit uint8_t low = 0xAB; uint8_t high = 0xCD; uint16_t packed = (high << 8) | low; // 0xCDAB // Unpack uint8_t extracted_low = packed & 0xFF; uint8_t extracted_high = (packed >> 8) & 0xFF; -
Hash Calculation
cunsigned int hash = 0; for (int i = 0; i < len; i++) { hash = (hash << 5) ^ str[i]; }
Important Considerations:
- Right shift behavior for signed numbers is implementation-dependent
- Bitwise operators have lower precedence than comparison operators
- Avoid bitwise operations on negative numbers
- Shift count must be less than the number of bits in the type