Set and Clear Bits in Golang
There are bitwise operators in golang for bit manipulation. However, there is an unusual NOT operator. golang uses the ^
operator for NOT.
Code
NOT of a number
a := 101
notOfA := a ^ a // 101 ^ 101 = 010
Setting a bit of a number
a := 101
b := 1 << 2 // second second bit
setBit := a | b // 101 | 010 = 111
Clear a bit
a := 101
b := 1 << 2 // second second bit
// 101 & ^(010) => 101 & 101 => 101
setBit := a &^ b
References
- https://github.com/onelang/OneLang/issues/23
- https://stackoverflow.com/questions/28432398/difference-between-some-operators-golang
Written with StackEdit