package main
import (
"fmt"
)
// setBit sets the bit at pos to 1
func setBit(n int, pos uint) int {
return n | (1 << pos) // OR with mask to set bit
}
// clearBit clears the bit at pos to 0
func clearBit(n int, pos uint) int {
return n &^ (1 << pos) // AND NOT with mask to clear bit
}
// toggleBit flips the bit at pos
func toggleBit(n int, pos uint) int {
return n ^ (1 << pos) // XOR with mask to flip bit
}
func main() {
n := 13 // binary 00001101
pos := uint(2)
set := setBit(n, pos)
clear := clearBit(n, pos)
toggle := toggleBit(clear, pos)
fmt.Printf("Set bit %d: %d (%.8b)\n", pos, set, set)
fmt.Printf("Clear bit %d: %d (%.8b)\n", pos, clear, clear)
fmt.Printf("Toggle bit %d: %d (%.8b)\n", pos, toggle, toggle)
}
return n | (1 << pos) // OR with mask to set bit
Set bit at position pos to 1 by ORing with mask
return n &^ (1 << pos) // AND NOT with mask to clear bit
Clear bit at position pos to 0 by AND NOT with mask
return n ^ (1 << pos) // XOR with mask to flip bit
Toggle bit at position pos by XORing with mask
Apply setBit to original number
clear := clearBit(n, pos)
Apply clearBit to original number
toggle := toggleBit(clear, pos)
Toggle bit on cleared number to demonstrate flip
Set bit 2: 13 (00001101)
Clear bit 2: 9 (00001001)
Toggle bit 2: 13 (00001101)