How to Use Bitwise Operators in Go

Use Go's bitwise operators like &, |, and << to manipulate individual bits in integer values for efficient flag management and data processing.

Use bitwise operators (&, |, ^, <<, >>, &^) directly on integer types to manipulate individual bits.

package main

import "fmt"

func main() {
    a := 0b1100 // 12
    b := 0b1010 // 10

    fmt.Printf("AND: %b\n", a & b)   // 1000 (8)
    fmt.Printf("OR:  %b\n", a | b)   // 1110 (14)
    fmt.Printf("XOR: %b\n", a ^ b)   // 0110 (6)
    fmt.Printf("NOT: %b\n", ^a)      // ...11110011 (two's complement)
    fmt.Printf("LShift: %b\n", a << 1) // 11000 (24)
    fmt.Printf("RShift: %b\n", a >> 1) // 0110 (6)
    fmt.Printf("ANDNOT: %b\n", a &^ b) // 0110 (6)
}