Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

single ampersand between 2 expressions

Tags:

go

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
}
like image 983
Maxim Yefremov Avatar asked Jun 09 '15 13:06

Maxim Yefremov


People also ask

What is single ampersand?

The single ampersand operator (&) evaluates both sides of the operator before arriving at its answer.

What does a single ampersand mean in C++?

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.

What does double ampersand mean?

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.

What is meaning of |= in C#?

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.


1 Answers

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

like image 156
Ainar-G Avatar answered Nov 15 '22 07:11

Ainar-G