C bitwise operators
Created By: chatGPT
In C, bitwise operators are used to perform operations on the bits of integer types. They are essential in tasks where direct manipulation of bits is necessary. There are several key bitwise operators:
1. AND operator (&): This operator takes two bit patterns and performs the AND operation on each pair of corresponding bits. The result will have a bit set to 1 only if both bits are 1.
int a = 12; // 1100 in binary
int b = 5; // 0101 in binary
int result = a & b; // result is 4 (0100 in binary)
2. OR operator (|): This operator performs the OR operation, resulting in a bit being set to 1 if at least one of the corresponding bits is 1.
int a = 12; // 1100 in binary
int b = 5; // 0101 in binary
int result = a | b; // result is 13 (1101 in binary)
3. XOR operator (^): The XOR operation sets a bit to 1 only if the corresponding bits of the operands are different.
int a = 12; // 1100 in binary
int b = 5; // 0101 in binary
int result = a ^ b; // result is 9 (1001 in binary)
4. NOT operator (~): The NOT operator inverts all the bits of its operand. Every 0 becomes a 1, and every 1 becomes a 0.
int a = 12; // 1100 in binary
int result = ~a; // result is -13 (in two's complement form)
5. Left shift operator (<<): This operator shifts all the bits of its operand to the left by a specified number of positions. New bits introduced on the right are set to 0.
int a = 3; // 0000 0011 in binary
int result = a << 2; // result is 12 (0000 1100 in binary)
6. Right shift operator (>>): This operator shifts all the bits of its operand to the right by a specified number of positions. For positive numbers, new bits on the left are set to 0.
Using bitwise operators can significantly enhance performance in certain applications such as graphics programming and low-level system programming. Remember to be cautious when using these operators, as they can lead to unexpected results if the operations are not understood properly.int a = 12; // 0000 1100 in binary
int result = a >> 2; // result is 3 (0000 0011 in binary)