Sunday 13 January 2019

Groovy: Bitwise operators


Below table summarizes the bitwise operators provided by Groovy.

Operator
Performs
Description
&
and
a & b
|
or
a | b
^
xor (Exclusive-OR)
a ^ b
~
negation
~a

Bit Wise AND(&), OR(|), Exclusive OR(^)
Below table summarizes the bitwise operators.
Bit1
Bit2
&
|
^
0
0
0
0
0
0
1
0
1
1
1
0
0
1
1
1
1
1
1
0

HelloWorld.groovy
a = 8
b = 9

println "a & b : ${a & b}"
println "a | b : ${a | b}"
println "a ^ b : ${a ^ b}"

Output
a & b : 8
a | b : 9
a ^ b : 1

Explanation
   a    = 0000 1000
   b    = 0000 1001
   a&b = 0000 1000

   a    = 0000 1000
   b    = 0000 1001
   a|b = 0000 10001

   a     = 0000 1000
   b     = 0000 1001
   a^b = 0000 0001
bitwise negation (~) operator
Negation (Inversion) operator change the bit value to zero, if it is one and change the bit value to one if it is zero.

Example
a = 7

a in binary format is       0 0 0 0 0 1 1 1
~(a) in binary format is  1 1 1 1 1 0 0 0
~(a) represents -8 in binary format.


HelloWorld.groovy
a = 7

println "a : ${a}"
println "~a : ${~a}"

Output
a : 7
~a : -8


Previous                                                 Next                                                 Home

No comments:

Post a Comment