Home >Backend Development >Golang >How can you set, clear, and check individual bits in Go using bitwise operations?

How can you set, clear, and check individual bits in Go using bitwise operations?

Barbara Streisand
Barbara StreisandOriginal
2024-11-10 03:43:02887browse

How can you set, clear, and check individual bits in Go using bitwise operations?

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 |= (1 << pos)
    return n
}

This function operates by shifting the number 1 left by the specified position (pos) using the << operator. This creates a mask that enables the corresponding bit. When you OR (|) this mask with the original integer, the target bit is set to 1 while preserving the other bits.

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 := ^(1 << pos)
    n &= mask
    return n
}

This 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 << pos)
    return val > 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.

The above is the detailed content of How can you set, clear, and check individual bits in Go using bitwise operations?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn