Last active
December 15, 2015 23:10
-
-
Save icholy/5338693 to your computer and use it in GitHub Desktop.
Bit flags in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// explicite | |
const ( | |
SAY_NIL = 0x00 // 0b00000000 | |
SAY_HELLO = 0x01 // 0b00000001 | |
SAY_FOO = 0x02 // 0b00000010 | |
SAY_BYE = 0x04 // 0b00000100 | |
) | |
// simpler | |
const ( | |
A = 0x01 << iota | |
B | |
C | |
D | |
E | |
F | |
G | |
) | |
func SayStuff(mode int) { | |
if mode&SAY_HELLO > 0 { | |
println("HELLO") | |
} | |
if mode&SAY_FOO > 0 { | |
println("FOO") | |
} | |
if mode&SAY_BYE > 0 { | |
println("BYE") | |
} | |
} | |
func main() { | |
/* | |
SAY_HELLO 0b00000001 OR | | |
SAY_FOO 0b00000010 | |
-------------------------- | |
0b00000011 OR | | |
SAY_BYE 0b00000100 | |
-------------------------- | |
0b00000111 | |
mode 0b00000111 AND & | |
SAY_HELLO 0b00000001 | |
-------------------------- | |
0b00000001 > 0 | |
*/ | |
SayStuff(SAY_HELLO | SAY_FOO | SAY_BYE) | |
SayStuff(SAY_NIL) | |
// Example 2 | |
mode := A | C | G | E | |
if mode&A != 0 { | |
println("A is set") | |
} | |
if mode&B != 0 { | |
println("B is set") | |
} | |
if mode&C != 0 { | |
println("C is set") | |
} | |
if mode&D != 0 { | |
println("D is set") | |
} | |
if mode&E != 0 { | |
println("E is set") | |
} | |
if mode&F != 0 { | |
println("F is set") | |
} | |
if mode&G != 0 { | |
println("G is set") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment