C Bitwise Operators
In this page:
Bitwise AND (&)
& compares two numbers bit by bit and produces a 1 in each position where both operands have a 1, and a 0 everywhere else -- often used to check or isolate specific bits within a value, like reading configuration flags.
Example: Bitwise AND (&)
#include <stdio.h>
int main() {
int a = 6, b = 3;
printf("%d", a & b);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Bitwise OR (|)
| compares two numbers bit by bit and produces a 1 in each position where at least one operand has a 1 -- commonly used to turn on specific bits without disturbing the others, such as setting a flag inside a bitmask.
Example: Bitwise OR (|)
#include <stdio.h>
int main() {
int a = 6, b = 3;
printf("%d", a | b);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Bitwise XOR (^)
^ (XOR) produces a 1 in each bit position where the two operands differ, and a 0 where they match -- a classic use is toggling a bit on or off, or swapping two values without a temporary variable.
Example: Bitwise XOR (^)
#include <stdio.h>
int main() {
int a = 6, b = 3;
printf("%d", a ^ b);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Bitwise NOT ()
~ is a unary operator that flips every bit of its single operand -- every 1 becomes 0 and every 0 becomes 1 -- which for a signed integer effectively produces its bitwise complement, not simply its negative.
Example: Bitwise NOT ()
#include <stdio.h>
int main() {
int a = 5;
printf("%d", ~a);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Shift Operators (<< and >>)
<< shifts all bits left by a given number of positions (equivalent to multiplying by a power of 2), while >> shifts them right (roughly equivalent to integer division by a power of 2) -- both are much faster than actual multiplication or division.
Example: Shift Operators (<< and >>)
#include <stdio.h>
int main() {
int a = 4;
printf("%d %d", a << 1, a >> 1);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: