C Language | Introduction to C | Bit Operations
Bitwise operators manipulate individual bits in integer values.
Bitwise Operators
| Operator | Meaning |
|---|---|
& |
bitwise AND |
| ` | ` |
^ |
bitwise XOR |
~ |
one’s complement |
&=, ` |
=, ^=` |
AND produces 1 only when both bits are 1. It is useful for extracting selected bits with a mask.
0101 1100
& 0000 1111
------------
0000 1100
Code 1
#include <stdio.h>
int main() {
char ch5 = '5';
printf("ch5: %%c = %c, %%X = %X, numeric = %d\n" , ch5 , ch5 , ch5 & 0x0F);
return 0;
}
OR produces 1 when either bit is 1. XOR produces 1 when the two bits differ. Complement reverses every bit.
Code 2
#include <stdio.h>
int main() {
unsigned int value = 0xCC33CC33;
printf("~%X = %X\n" , value , ~value);
return 0;
}
Bit Shifts
Shift operators move bits left or right.
| Operator | Meaning |
|---|---|
<< |
left shift |
>> |
right shift |
<<=, >>= |
compound assignment forms |
value << count
value >> count
For unsigned values, shifting left by one position corresponds to multiplication by two when no significant bit is discarded. Shifting right by one corresponds to division by two.
Code 3
#include <stdio.h>
int main() {
unsigned int value = 100;
printf("value / 4 = %u\nvalue * 4 = %u\n" , value >> 2 , value << 2);
return 0;
}
Use unsigned values when portable bit manipulation matters. Right-shifting a negative signed integer is implementation-defined, and shifts that exceed the valid width must be avoided.