Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

& | ^ ~ << >> >>>

Bitwise operators work with individual bits of integers: AND, OR, XOR, NOT and shifts.

Available since: Java 1.0

Syntax

a & b   a | b   a ^ b   ~a   a << n   a >> n   a >>> n

Examples

AND, OR, XOR and NOT for 12 (1100) and 10 (1010):

void main() {
    int a = 0b1100;
    int b = 0b1010;
 
    IO.println(a & b);
    IO.println(a | b);
    IO.println(a ^ b);
    IO.println(~a);
    IO.println(Integer.toBinaryString(a & b));
}

Output:

8
14
6
-13
1000

Shifts: << multiplies by a power of two, >> divides keeping the sign, >>> fills the vacated bits with zeros:

void main() {
    IO.println(1 << 4);
    IO.println(100 >> 2);
    IO.println(-16 >> 2);
    IO.println(-16 >>> 28);
}

Output:

16
25
-4
15

A set of flags in one number: setting, checking and clearing a bit:

static final int READ = 1;
static final int WRITE = 1 << 1;
static final int EXEC = 1 << 2;
 
void main() {
    int perms = READ | WRITE;
    IO.println((perms & WRITE) != 0);
    IO.println((perms & EXEC) != 0);
 
    perms &= ~WRITE;
    IO.println(perms);
}

Output:

true
false
1

Notes

Bitwise operators have low precedence: perms & WRITE != 0 does not compile, you need parentheses (perms & WRITE) != 0. With boolean the & and | operators also work, but unlike && and || they always evaluate both sides. For a set of enum flags EnumSet is clearer. There are compound forms: &=, |=, ^=, <<=.

See also

  • && || ! — Logical AND, OR and NOT for boolean values.
  • Integer.toBinaryString() — Writes a number in binary. Related methods are toHexString() and toOctalString().
  • EnumSet — A set of values of one enum. Works like a set of bit flags, but with readable code.
  • += -= *= /= — Performs an operation and stores the result back in the same variable.

Related recipes

In the tutorial

  • Bitwise operators — Java bitwise operators: & | ^ ~, the shifts << >> >>>, binary form with Integer.toBinaryString, flags and masks.

Thanks for reading!

Donate to the site — we work hard for you.