Bitwise Operators
Bitwise operators perform operations on individual bits, and the result is also always a bit. They can work with integral numeric types. There are six bitwise operators:
1. `~` – Complement
2. `&` – AND
3. `|` – OR
4. `^` – Exclusive OR
5. `<<` – Left shift
6. `>>` – Right shift
Example in C:
#include <stdio.h> int main() { unsigned int a = 60; // 60 in binary: 0011 1100 unsigned int b = 13; // 13 in binary: 0000 1101 int result; // Bitwise AND result = a & b; // result = 12 (0000 1100) printf("a & b = %d\n", result); // Bitwise OR result = a | b; // result = 61 (0011 1101) printf("a | b = %d\n", result); // Bitwise XOR result = a ^ b; // result = 49 (0011 0001) printf("a ^ b = %d\n", result); // Bitwise NOT result = ~a; // result = -61 (1100 0011) printf("~a = %d\n", result); // Left shift result = a << 2; // result = 240 (1111 0000) printf("a << 2 = %d\n", result); // Right shift result = a >> 2; // result = 15 (0000 1111) printf("a >> 2 = %d\n", result); return 0; }
Logical Operators:
Logical operators compare bits of the given object and always return a Boolean result. They work with Boolean variables or expressions. There are three basic operands:
1. `&&` – Logical AND
2. `||` – Logical OR
3. `!` – Logical NOT
#include <stdio.h> int main() { int x = 5, y = 10, z = 5; // Logical AND if (x > 0 && y > 0) printf("x and y are both greater than 0\n"); // Logical OR if (x == 5 || y == 5) printf("At least one of x or y is equal to 5\n"); // Logical NOT if (!(x == y)) printf("x is not equal to y\n"); return 0; }
Team Answered question April 13, 2024