Java Reference ยท Operators
Java bitwise operators
Reference for Java bitwise operators &, |, ^ and ~: how they work on int and long, masks and flags, two's complement, and Integer helper methods.
Bitwise operators work on the individual bits of integer values. & keeps the bits that are set in both operands, | keeps bits set in either, ^ keeps bits that differ, and the unary ~ flips every bit. They apply to byte, short, char, int and long; smaller types are first promoted to int.
They are used for flags and masks, low-level protocols, hashing and compact data structures. Integers use two's complement, so ~x equals -x - 1.
int mask = 0b1010; int bits = 0b0110 & mask; // 0b0010
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
a & b // AND a | b // OR a ^ b // XOR ~a // complement (unary)
| Operator | Bit result | Typical use |
|---|---|---|
& |
1 only if both bits are 1 | test or clear bits with a mask |
| |
1 if either bit is 1 | set bits |
^ |
1 if the bits differ | toggle bits |
~ |
flips every bit | build "all except" masks |
Usage notes
- Promotion.
byteandshortoperands becomeint, so~bof a negative byte gives anint. Mask with& 0xFFto get an unsigned byte value. - Mixed widths. If one operand is
long, the other is widened tolong. A negativeintwidens by sign extension, which fills the upper 32 bits with ones; mask with0xFFFFFFFFLto avoid that. - On booleans the same symbols are logical operators that do not short-circuit; see Logical operators.
&on anintand abooleandoes not compile. - Precedence is low.
x & 1 == 1parses asx & (1 == 1)and fails to compile. Always write(x & 1) == 1. - Helpers.
Integer.bitCount,Integer.highestOneBit,Integer.numberOfTrailingZeros,Integer.reverseandLong.*equivalents are clearer than hand-rolled loops. For many flags,EnumSetorBitSetread better. - Literals. Use
0bfor binary,0xfor hex and underscores for readability (0b1100_1010). - Shifts have their own operators; see Shift operators.