Bit Manipulation in Go: Setting and Clearing Individual Bits
In Go, manipulating individual bits within an integer can be a useful technique for various applications. One way to achieve this is through bitwise operations.
Setting a Bit
To set the bit at a specific position, you can use the following function:
func setBit(n int, pos uint) int { n |= (1This function operates by shifting the number 1 left by the specified position (pos) using the
Clearing a Bit
To clear a bit at a specific position, you can use the following function:
func clearBit(n int, pos uint) int { mask := ^(1This function creates a mask by inverting the bit at the target position using the ^ operator. The resulting mask effectively has the target bit set to 0. When you AND (&) this mask with the original integer, the target bit is cleared while the other bits remain unaffected.
Checking if a Bit is Set
Finally, you can check if a bit is set using the following function:
func hasBit(n int, pos uint) bool { val := n & (1 0 }This function performs an AND operation between the integer and a mask that has the corresponding bit set to 1. If the result is greater than 0, it indicates that the target bit is set, and the function returns true. Otherwise, it returns false.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3