How to Manipulate Bits in Go
Working with individual bits in an integer is a common task in programming. In Go, there are several ways to achieve this, including the following:
Setting a Bit
To set a particular bit in an integer, you can use the bitwise OR operator (|). For instance:
// Sets the 7th bit in the integer n. func setBit(n int, pos uint) int { return n | (1 << pos) }
Clearing a Bit
To clear a bit, you can use the bitwise AND operator (&) with a mask. Here's an example:
// Clears the 7th bit in the integer n. func clearBit(n int, pos uint) int { mask := ^(1 << pos) return n & mask }
Checking if a Bit is Set
To check if a particular bit is set, you can use the bitwise AND operator again:
// Returns true if the 7th bit is set in the integer n, false otherwise. func hasBit(n int, pos uint) bool { return (n & (1 << pos)) > 0 }
These functions provide a flexible and efficient way to manipulate individual bits in Go, enabling you to perform bitwise operations with precision.
The above is the detailed content of How to Manipulate Individual Bits in Go: Setting, Clearing, and Checking?. For more information, please follow other related articles on the PHP Chinese website!