Bitwise Operators in Go
- Bitwise operators are used to perform operations at the binary level. They work on the individual bits of integer values.
Bitwise Operators in Go (Point-Wise)
1.AND Operator (&)
- Compares each bit of two numbers.
- Returns 1 only if both corresponding bits are 1.
Example:
5 & 3 gives 1 because 0101 & 0011 = 0001.
2.OR Operator (|)
- Compares each bit of two numbers.
- Returns 1 if either of the corresponding bits is 1.
Example:
5 | 3 gives 7 because 0101 | 0011 = 0111.
3.XOR Operator (^)
- Returns 1 only if the corresponding bits are different.
Example:
5 ^ 3 gives 6 because 0101 ^ 0011 = 0110.
4.AND NOT Operator (&^)
- Clears bits from the left operand where the right operand has bits set.
Example:
5 &^ 3 gives 4 because 0101 &^ 0011 = 0100.
5.Left Shift Operator (<<)
- Shifts bits to the left, adding zeros from the right.
- Each shift multiplies the number by 2.
Example:
5 << 1 gives 10 because 0101 becomes 1010.
6.Right Shift Operator (>>)
- Shifts bits to the right, discarding bits on the right.
- Each shift divides the number by 2.
Example:
5 >> 1 gives 2 because 0101 becomes 0010.