Home >Backend Development >Golang >How to Set, Clear, and Check Individual Bits in Go?

How to Set, Clear, and Check Individual Bits in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 10:21:03645browse

How to Set, Clear, and Check Individual Bits in Go?

Bit Manipulation in Go: Setting and Clearing Individual Bits

Bit manipulation is essential when working with the underlying data representation in computer systems. In Go, you can manipulate individual bits of an integer to achieve specific outcomes. Here's how you can set and clear bits in Go:

Setting a Bit

To set a bit in an integer n at position pos, use the following function:

// Sets the bit at pos in the integer n.
func setBit(n int, pos uint) int {
    // Shift 1 the specified number of spaces.
    bit := 1 << pos
    // OR the resulting bit mask with n.
    return n | bit
}

Clearing a Bit

To clear a bit at position pos in n, use this function:

// Clears the bit at pos in n.
func clearBit(n int, pos uint) int {
    // Shift 1 the specified number of spaces.
    bit := 1 << pos
    // Flip every bit in the mask using XOR operator.
    mask := ^bit
    // AND mask with n to unset the target bit.
    return n & mask
}

Checking if a Bit is Set

You can also check if a bit is set at a particular position using this function:

func hasBit(n int, pos uint) bool {
    // Shift 1 the specified number of spaces.
    bit := 1 << pos
    // AND the resulting bit mask with n.
    val := n & bit
    // Return true if val is greater than 0.
    return (val > 0)
}

With these functions, you can perform precise bit manipulations in your Go programs.

The above is the detailed content of How to Set, Clear, and Check Individual Bits in Go?. 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