Skip to content

Instantly share code, notes, and snippets.

@nosilex
Created May 10, 2023 13:10
Show Gist options
  • Save nosilex/2bdc5615ef8a4e4cf4428890edad3a22 to your computer and use it in GitHub Desktop.
Save nosilex/2bdc5615ef8a4e4cf4428890edad3a22 to your computer and use it in GitHub Desktop.
Bits operations with GO
package main
import (
"fmt"
)
type Bits uint8
const (
F0 Bits = 1 << iota
F1
F2
)
func Set(b, flag Bits) Bits { return b | flag }
func Clear(b, flag Bits) Bits { return b &^ flag }
func Toggle(b, flag Bits) Bits { return b ^ flag }
func Has(b, flag Bits) bool { return b&flag != 0 }
func main() {
var b Bits
b = Set(b, F0)
b = Toggle(b, F2)
for i, flag := range []Bits{F0, F1, F2} {
fmt.Println(i, Has(b, flag))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment