In C, bitwise operators are used to perform bit-level operations on variables. These operators work on the individual bits of a variable and are often used for low-level programming tasks, such as working with memory or manipulating hardware. The following are the bitwise operators in C:
- & (AND): The & operator performs a bit-level AND operation on two variables. For example:
int a = 5; // binary representation is 101
int b = 2; // binary representation is 010
int c = a & b; // c is now 0 (binary representation is 000)
- | (OR): The | operator performs a bit-level OR operation on two variables. For example:
int a = 5; // binary representation is 101
int b = 2; // binary representation is 010
int c = a | b; // c is now 7 (binary representation is 111)
- ^ (XOR): The ^ operator performs a bit-level XOR (exclusive OR) operation on two variables. For example:
int a = 5; // binary representation is 101
int b = 2; // binary representation is 010
int c = a ^ b; // c is now 7 (binary representation is 111)
- ~ (NOT): The ~ operator performs a bit-level NOT operation on a variable. For example:
int a = 5; // binary representation is 101
int b = ~a; // b is now -6 (binary representation is 11111010)
- << (left shift): The << operator shifts the bits of a variable to the left by a specified number of places. For example:
int a = 5; // binary representation is 101
int b = a << 1; // b is now 10 (binary representation is 1010)
-
(right shift): The >> operator shifts the bits of a variable to the right by a specified number of places. For example:
int a = 5; // binary representation is 101
int b = a >> 1; // b is now 2 (binary representation is 10)
It is important to use the correct bitwise operator based on the type of bit-level operation you want to perform. Using the wrong operator can result in errors or unexpected results in your code.