英文:
single ampersand between 2 expressions
问题
我正在查看Go语言源代码中的模块math/rand。我在那里找到了一行有趣的代码:
if n&(n-1) == 0 { // n是2的幂,可以进行位掩码
我只是好奇,n&(n-1)
是什么意思?
我可以理解n && (n-1)
。它是两个布尔表达式之间的“与”运算符。我可以理解&n
。它是n
变量的地址。但是n&(n-1)
是什么意思,我无法理解。
完整的方法代码:
// Int63n以int64的形式返回[0,n)范围内的非负伪随机数。
// 如果n <= 0,则会引发panic。
func (r *Rand) Int63n(n int64) int64 {
if n <= 0 {
panic("invalid argument to Int63n")
}
if n&(n-1) == 0 { // n是2的幂,可以进行位掩码
return r.Int63() & (n - 1)
}
max := int64((1 << 63) - 1 - (1<<63)%uint64(n))
v := r.Int63()
for v > max {
v = r.Int63()
}
return v % n
}
英文:
I was looking at the Go language source code, module math/rand. I found there one interesting line
if n&(n-1) == 0 { // n is power of two, can mask
I'm just curious, what does n&(n-1)
mean?
I would understand n && (n-1)
. It would be AND
operator between 2 boolean expressions. I would understand &n
. It's address of n
variable. But what is n&(n-1)
I cannot figure out.
Full method code:
// Int63n returns, as an int64, a non-negative pseudo-random number in [0,n).
// It panics if n <= 0.
func (r *Rand) Int63n(n int64) int64 {
if n <= 0 {
panic("invalid argument to Int63n")
}
if n&(n-1) == 0 { // n is power of two, can mask
return r.Int63() & (n - 1)
}
max := int64((1 << 63) - 1 - (1<<63)%uint64(n))
v := r.Int63()
for v > max {
v = r.Int63()
}
return v % n
}
答案1
得分: 9
这是按位与运算符。
// 输出2,因为3 (0x0011) & 2 (0x0010) = 2 (0x0010)
fmt.Println(3 & 2)
http://play.golang.org/p/JFto4ZHUEC
英文:
This is the bitwise AND operator.
// Prints 2, because 3 (0x0011) & 2 (0x0010) = 2 (0x0010)
fmt.Println(3 & 2)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论