In Golang, how do you set and clear individual bits of an integer? For example, functions that behave like this:
clearBit(129, 7) // returns 1 setBit(1, 7) // returns 129
Clearing a bitUse the bitwise AND operator ( & ) to clear a bit. number &= ~(1UL << n); That will clear the n th bit of number . You must invert the bit string with the bitwise NOT operator ( ~ ), then AND it.
Clearing a bit means that if K-th bit is 1, then clear it to 0 and if it is 0 then leave it unchanged. Toggling a bit means that if K-th bit is 1, then change it to 0 and if it is 0 then change it to 1.
Here's a function to set a bit. First, shift the number 1 the specified number of spaces in the integer (so it becomes 0010, 0100, etc). Then OR it with the original input. This leaves the other bits unaffected but will always set the target bit to 1.
// Sets the bit at pos in the integer n. func setBit(n int, pos uint) int { n |= (1 << pos) return n }
Here's a function to clear a bit. First shift the number 1 the specified number of spaces in the integer (so it becomes 0010, 0100, etc). Then flip every bit in the mask with the ^
operator (so 0010 becomes 1101). Then use a bitwise AND, which doesn't touch the numbers AND
'ed with 1, but which will unset the value in the mask which is set to 0.
// Clears the bit at pos in n. func clearBit(n int, pos uint) int { mask := ^(1 << pos) n &= mask return n }
Finally here's a function to check whether a bit is set. Shift the number 1 the specified number of spaces (so it becomes 0010, 0100, etc) and then AND it with the target number. If the resulting number is greater than 0 (it'll be 1, 2, 4, 8, etc) then the bit is set.
func hasBit(n int, pos uint) bool { val := n & (1 << pos) return (val > 0) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With