如何设置和清除Go中的单个位?

如何设置和清除Go中的单个位?,go,bit-manipulation,Go,Bit Manipulation,在Golang中,如何设置和清除整数的各个位?例如,行为如下的函数: clearBit(129, 7) // returns 1 setBit(1, 7) // returns 129 // Clears the bit at pos in n. func clearBit(n int, pos uint) int { n &^= (1 << pos) return n } // Clears the bit at pos in n. func

在Golang中,如何设置和清除整数的各个位?例如,行为如下的函数:

 clearBit(129, 7) // returns 1
 setBit(1, 7)     // returns 129
// Clears the bit at pos in n.
func clearBit(n int, pos uint) int {
    n &^= (1 << pos)
    return n
}
// Clears the bit at pos in n.
func clearBit(n int, pos uint) int {
    return n &^ (1 << pos)
}

这里有一个函数来设置位。首先,将数字1移位为整数中指定的空格数(使其变为0010100等)。然后,使用原始输入对其进行修改。这使其他位不受影响,但将始终将目标位设置为1

// Sets the bit at pos in the integer n.
func setBit(n int, pos uint) int {
    n |= (1 << pos)
    return n
}
最后,这里有一个函数来检查是否设置了位。将数字1移动指定的空格数(使其变为0010、0100等),然后将其与目标数字相加。如果结果数字大于0(将为1、2、4、8等),则设置位

func hasBit(n int, pos uint) bool {
    val := n & (1 << pos)
    return (val > 0)
}
func hasBit(n int,pos uint)bool{
val:=n&(10)
}

还有一个紧凑的符号来清除位。它的运算符是
&^
,称为“and not”

使用此运算符,
clearBit
函数可以这样编写:

 clearBit(129, 7) // returns 1
 setBit(1, 7)     // returns 129
// Clears the bit at pos in n.
func clearBit(n int, pos uint) int {
    n &^= (1 << pos)
    return n
}
// Clears the bit at pos in n.
func clearBit(n int, pos uint) int {
    return n &^ (1 << pos)
}
//清除n中位置处的位。
func clearBit(n int,pos uint)int{

n&^=(1注意只写
x&=^(1)可能更简单。贪婪,我只是提取了变量以帮助清晰/可读性。编译器可能也在进行这些优化。