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
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
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.
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 numbersAND
'ed with 1, but which will unset the value in the mask which is set to 0.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.
There is also a compact notation to clear a bit. The operator for that is
&^
and called "and not".Using this operator the
clearBit
function can be written like this:Or like this: