Bitwise Operations

From Groovy 1.0 beta 10, Groovy supports bitwise operations:
<<. >>, >>>, |, &, ^, and ~.

Operator Symbol Meaning
<< Bitwise Left Shift Operator
>> Bitwise Right Shift Operator
>>> Bitwise Unsigned Right Shift Operator
| Bitwise Or Operator
& Bitwise And Operator
^ Bitwise Xor Operator
~ Bitwise Negation Operator
<<= Bitwise Left Shift Assign Operator
>>= Bitwise Right Shift Assign Operator
>>>= Bitwise Unsigned Right Shift Assign Operator
|= Bitwise Or Assign Operator
&= Bitwise And Assign Operator
^= Bitwise Xor Operator

For example,

assert (1 << 2) == 4         // bitwise left shift
assert (4 >> 1) == 2         // bitwise right shift
assert (15 >>> 1) == 7       // bitwise unsigned right shift
assert (3 | 6) == 7          // bitwise or
assert (3 & 6) == 2          // bitwise and
assert (3 ^ 6) == 5          // bitwise xor
assert (~0xFFFFFFFE) == 1    // bitwise negation

Labels

 
(None)
  1. May 25, 2006

    Karsten Tinnefeld says:

    &nbsp; Groovy hex numbers are seemingly fixed length no more.  assert (0xFFFFFF...

      Groovy hex numbers are seemingly fixed length no more.

     assert (~0xFFFFFFFE) == 1    // bitwise negation

    as of jsr-05 yields

     Exception thrown: java.lang.AssertionError: Expression: (4294967294 == 1)
  2. Mar 21

    Pascal Chouinard says:

    I have the same error, when changing the last line for the following it works: a...

    I have the same error, when changing the last line for the following it works:

    assert (int)~0xFFFFFFFE == 1    // bitwise negation

    It seems the number is evaluated to a long:

    println 0xFFFFFFFE.class

    output: class java.lang.Long