Home »
Golang
Golang Bitwise Operators
Last Updated : April 19, 2025
Bitwise operators are used for performing operations on bits, i.e., bitwise operators work on bits and perform the bit-by-bit operation, i.e., the bitwise operators are the operators used to perform bitwise operations on bit patterns or binary numerals that involve the manipulation of individual bits.
List of Bitwise Operators
Operator |
Description |
Example x:=5 y:=3 |
Bitwise AND (&) |
It returns 1 in each bit position for which the corresponding bits of both operands are 1s. |
x & y returns 1 |
Bitwise OR (|) |
It returns 1 in each bit position for which the corresponding bits of either or both operands are 1s. |
x | y returns 7 |
Bitwise XOR (^) |
It returns 1 in each bit position for which the corresponding bits of either but not both operands are 1s. |
x ^ y returns 6 |
Bitwise Left Shift (<<) |
It shifts the first operand to the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. |
x << 2 returns 20 |
Bitwise Right Shift (>>) |
It shifts the first operand to the specified number of bits to the right. Excess bits shifted off to the right are discarded. |
x >> 1 returns 1 |
Example of Bitwise Operators
The below Golang program is demonstrating the example of bitwise operators.
// Golang program demonstrate the
// example of bitwise operators
package main
import "fmt"
func main() {
x := 5
y := 3
result := 0
result = (x & y)
fmt.Println(x, "&", y, "=", result)
result = (x | y)
fmt.Println(x, "|", y, "=", result)
result = (x ^ y)
fmt.Println(x, "^", y, "=", result)
result = (x << 2)
fmt.Println(x, "<<", 2, "=", result)
result = (x >> 2)
fmt.Println(x, ">>", 2, "=", result)
}
Output:
5 & 3 = 1
5 | 3 = 7
5 ^ 3 = 6
5 << 2 = 20
5 >> 2 = 1
Go Bitwise Operators Exercise
Select the correct option to complete each statement about bitwise operators in Go.
- The operator ___ is used for the bitwise AND operation in Go.
- The operator ___ is used for the bitwise OR operation in Go.
- The operator ___ is used for the bitwise XOR operation in Go.
- The operator ___ is used to shift the bits to the left in Go.
- The operator ___ is used to shift the bits to the right in Go.
Advertisement
Advertisement