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
}
The single ampersand operator (&) evaluates both sides of the operator before arriving at its answer.
Description. The bitwise AND operator in C++ is a single ampersand & , used between two other integer expressions. Bitwise AND operates on each bit position of the surrounding expressions independently, according to this rule: if both input bits are 1, the resulting output is 1, otherwise the output is 0.
In programming, a double ampersand is used to represent the Boolean AND operator such as in the C statement, if (x >= 100 && x >= 199). In HTML, the ampersand is used to code foreign letters and special characters such as the copyright and trademark symbols. See ampersand codes and address operator.
Equality operator (==), returns true for operands whose values are equal. Inequality operator (! =), returns false if two operands are equal. Less than relational operator (<), defined for all numeric and enumeration types and returns true if the first operand is less than the second operand.
This is the bitwise AND operator.
// Prints 2, because 3 (0x0011) & 2 (0x0010) = 2 (0x0010)
fmt.Println(3 & 2)
http://play.golang.org/p/JFto4ZHUEC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With