Home »
Golang
Golang Bitwise Operators
By IncludeHelp Last updated : October 05, 2024
Golang Bitwise Operators
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 Golang 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 Golang 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