Go by Example: Bitwise Operations
Go 1.23
Go supports standard bitwise operators for low-level data manipulation. This example demonstrates AND, OR, XOR, bit shifting, and the unique "bit clear" (AND NOT) operator.
Code
package main
import "fmt"
func main() {
// 1. Basic Operators
// a: 1010 (10)
// b: 0011 (3)
a := 10
b := 3
fmt.Printf("a: %04b (%d)\n", a, a)
fmt.Printf("b: %04b (%d)\n", b, b)
// AND (&): 1 if both bits are 1
// 1010 & 0011 = 0010 (2)
fmt.Printf("a & b: %04b (%d)\n", a&b, a&b)
// OR (|): 1 if either bit is 1
// 1010 | 0011 = 1011 (11)
fmt.Printf("a | b: %04b (%d)\n", a|b, a|b)
// XOR (^): 1 if bits are different
// 1010 ^ 0011 = 1001 (9)
fmt.Printf("a ^ b: %04b (%d)\n", a^b, a^b)
// 2. Bit Clear (&^)
// Unique to Go. Clears bits in 'x' that are set in 'y'.
// x &^ y is equivalent to x & (^y)
// 1010 &^ 0011 = 1000 (8)
fmt.Printf("a &^ b: %04b (%d)\n", a&^b, a&^b)
// 3. Bit Shifting
// Left shift (<<) multiplies by 2^n
// Right shift (>>) divides by 2^n
n := 1 // 0001
fmt.Printf("1 << 3: %04b (%d)\n", n<<3, n<<3) // 1000 (8)
fmt.Printf("8 >> 2: %04b (%d)\n", 8>>2, 8>>2) // 0010 (2)
}
Explanation
Bitwise operations allow you to manipulate individual bits of integer data. While less common in high-level web development, they are crucial for systems programming, cryptography, network protocols, and optimizing storage (flags). Go provides the standard set of operators found in C, plus a unique "bit clear" operator.
The operators include:
&(AND): Sets bit to 1 if both operands have 1.|(OR): Sets bit to 1 if either operand has 1.^(XOR): Sets bit to 1 if operands are different.&^(AND NOT): Clears bits.x &^ yturns off bits inxthat are 1 iny.<</>>(Shifts): Moves bits left or right, filling with zeros (for unsigned) or sign bit (for signed).
Go uses the caret ^ for both XOR (binary operator) and Bitwise NOT (unary operator). This is different from C/Java which use ~ for NOT.
Code Breakdown
12-13
Printing binary representations. The verb '%b' formats the number in base-2. '%04b' ensures it prints at least 4 digits, padding with zeros if necessary.
17
The AND operator. Useful for masking (extracting) specific bits. For example, 'x & 1' tells you if a number is odd or even.
31
The Bit Clear operator (&^). This is a Go specialty. It's a concise way to say "force these bits to zero". It's often used to unset flags in a bitmask.
37
Left shift. Shifting a 1 three positions to the left (0001 -> 1000) is equivalent to multiplying by 2^3 (8). This is extremely fast arithmetic for powers of 2.

