【问题标题】:single ampersand between 2 expressions两个表达式之间的单个 &
【发布时间】:2021-09-05 22:34:02
【问题描述】:

我正在查看 Go 语言源代码,模块 math/rand。我在那里发现了一条有趣的线

if n&(n-1) == 0 { // n is power of two, can mask

我只是好奇,n&(n-1) 是什么意思?

我会理解n && (n-1)。这将是 AND 两个布尔表达式之间的运算符。我会理解&n。它是n 变量的地址。但是n&(n-1)是什么我想不通。

完整方法代码:

// 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
}

【问题讨论】:

标签: go


【解决方案1】:

这是bitwise AND 运算符。

// Prints 2, because 3 (0x0011) & 2 (0x0010) = 2 (0x0010)
fmt.Println(3 & 2)

http://play.golang.org/p/JFto4ZHUEC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-02
    • 2020-06-09
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    相关资源
    最近更新 更多