What's the use of & in Programming languages?
I have seen the use of &
in many programming language and since I love groovy a lot I tried the following code to find the use of &
:
a = 1 ;
println a & 2
I'm getting the output as 0
. When I change the values of a
I get different answer's.
So any one can say whats the use of &
in programming languages like Groovy in simple english, possibly with开发者_如何学C an simple example in any language?
Thanks in advance.
&
is usually either bitwise-and (on integer arguments) or non-short-circuiting logical and (on boolean arguments).
bitwise-and returns a series of bits (usually represented as an int
type) that have only the bits in common set
18 == 10010
6 == 00110
18 & 6 == 2 == 00010
This seems to be what is happening in your Groovy code. 1 & 2 == 0
since 1 and 2 share no bits in common.
Non-short-ciruiting logical and is similar to &&
but
if (f() && g()) // g is only called if f returns false
if (f() & g()) // g is called even when f returns false
In languages that allow operator overloading, libraries sometimes overloaded &
to do set intersection, or element-wise bit-intersection.
Searching "Groovy Operator" in Google, the first result yields: http://groovy.codehaus.org/Operators
In general all operators supported in Java are identical in Groovy.
Further in http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html:
bitwise AND &
Searching for "Bitwise AND" in Google, the first result is: http://en.wikipedia.org/wiki/Bitwise_operation#AND
AND
A bitwise AND takes two binary representations of equal length and performs the logical AND operation on each pair of corresponding bits. For each pair, the result is 1 if the first bit is 1 AND the second bit is 1; otherwise, the result is 0. For example:
0101 (decimal 5) AND 0011 (decimal 3) = 0001 (decimal 1)
it takes less than 5 minute to work all that out.
精彩评论