Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 201 ยท Operators

Bitwise and Shift Operators

Learn Java's bitwise operators & | ^ ~ and the shifts << >> >>>, how two's complement works, and how to use flags, masks and Integer bit helpers.

Every int in Java is really a row of 32 bits, each one either 0 or 1. Most of the time you never think about them: you add, compare and print numbers. But sometimes you need to reach inside a number and work with individual bits, for example to pack eight on/off settings into one byte, pull the red channel out of a color, or check whether a number is a power of two.

Bitwise operators do exactly that. They work on each bit position separately instead of on the number as a whole. Shift operators slide all the bits left or right. This lesson explains both, along with the two's complement system that Java uses for negative numbers, and the practical patterns (flags, masks and packed fields) you'll meet in real code.

Binary in one minute

In binary, each position is worth twice the one to its right: 1, 2, 4, 8, 16 and so on. The number 13 is 8 + 4 + 1, so in binary it is 1101. Java lets you write binary literals with the 0b prefix and print any int in binary with Integer.toBinaryString:

Java
int thirteen = 0b1101;                  // 13
int mask = 0b1111_0000;                 // underscores for readability: 240
IO.println(Integer.toBinaryString(13)); // 1101
IO.println(Integer.toHexString(240));   // f0

Hexadecimal (0x prefix) is common in bit-level code because each hex digit stands for exactly four bits: 0xF0 is 1111 0000. Primitive Data Types covers all the literal forms.

The four bitwise operators

&, | and ^ take two integers and combine them bit by bit. ~ takes one integer and flips every bit.

Operator Name A result bit is 1 when
& AND both input bits are 1
| OR at least one input bit is 1
^ XOR (exclusive OR) the two input bits differ
~ NOT (complement) the input bit is 0

These are the same symbols you saw on booleans in Comparison and Logical Operators. Think of each bit as a tiny boolean, with 1 as true and 0 as false, and the rules carry over exactly. Unlike && and ||, there is no short-circuiting: every bit is computed.

Java AND, OR and XOR bit by bit

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.

Read the output column by column. In the leftmost column both a and b have a 1, so all three results have a 1 there. In the rightmost column both have 0, so all three have 0. The two middle columns differ between a and b, so & gives 0, while | and ^ give 1.

Bitwise operators work on int and long. If you use them on byte, short or char, the values are first promoted to int, just like with arithmetic.

Negative numbers and two's complement

To understand ~ and the shift operators, you need to know how Java stores negative integers. It uses two's complement: the leftmost bit (the sign bit) is 1 for negative numbers, and -x is stored as "flip every bit of x, then add 1".

That system has a few consequences you can see directly:

Java Two's complement up close

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.

  • -1 is all ones: 32 one-bits. Adding 1 to it overflows to all zeros, which is 0, exactly as it should.
  • ~x equals -x - 1, because flipping the bits is the first half of negating. So ~5 is -6 and ~-1 is 0.
  • The range is lopsided. An int goes from -2,147,483,648 to 2,147,483,647. There is one more negative number than positive, so -Integer.MIN_VALUE overflows back to Integer.MIN_VALUE. (Working with Numbers shows other overflow cases.)

Integer.toBinaryString prints negative numbers with all 32 bits, but drops leading zeros for positive ones. Keep that in mind when you compare output.

Shift operators

Shift operators move every bit of the left operand by the number of positions given on the right:

Operator Name What it does
<< left shift moves bits left, filling with 0 on the right
>> signed right shift moves bits right, copying the sign bit into the left
>>> unsigned right shift moves bits right, filling with 0 on the left

Shifting left by n multiplies by 2โฟ (as long as nothing falls off the top). Shifting right with >> divides by 2โฟ, rounding down toward negative infinity, which differs from / for negative numbers. >>> treats the number as if it had no sign at all, so for negative values it gives a large positive result.

Java Shifting left and right

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.

The last two lines are a famous trap. For an int, Java uses only the lowest five bits of the shift distance, so 1 << 32 is really 1 << 0, which is 1, not 0 or an error. For a long, it uses the lowest six bits. If you need bit positions above 31, make the left operand a long with the L suffix: 1L << 40.

Shifting a negative byte with >>> doesn't do what you expect. The byte is promoted to an int first, with its sign extended, so (byte) -1 >>> 4 gives 268435455, and casting it back to byte gives -1 again. To treat a byte as an unsigned value from 0 to 255, mask it first: (b & 0xFF) >>> 4.

Don't replace * 2 or / 4 with shifts to "speed up" ordinary arithmetic. The JIT compiler already does that where it is safe, and the shift version is harder to read and wrong for negative numbers with /. Use shifts when you are genuinely working with bits.

Flags: many booleans in one int

The most common real-world use of bitwise operators is a bit set or flags field: each bit position stands for one on/off option. Give each option a constant with a single 1-bit, then use four standard patterns:

Task Code
Turn a flag on flags |= FLAG;
Turn a flag off flags &= ~FLAG;
Toggle a flag flags ^= FLAG;
Test a flag (flags & FLAG) != 0
Java File permissions as flags

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.

~WRITE is all ones except the WRITE bit, so &= with it clears that one bit and keeps every other bit as it was. Testing "has all of these" compares the masked value with the mask itself; "has any of these" checks for non-zero.

Always write the parentheses in (perms & READ) != 0. Because != has higher precedence than &, the version without parentheses is parsed as perms & (READ != 0), which mixes an int and a boolean and doesn't compile. Operator Precedence explains the ordering.

Flags packed into an int are fast and compact, and you'll see them in file formats, network protocols, graphics code and older APIs. In your own application code, an EnumSet of an enum is usually clearer, and it's implemented with exactly these bit tricks internally. See Enums and EnumMap, EnumSet, IdentityHashMap, WeakHashMap and BitSet.

Masks and packed fields

A mask selects some bits and hides the rest. Combined with shifts, masks let you store several small values in one number and take them apart again. A 24-bit RGB color is the classic example: 8 bits for red, 8 for green and 8 for blue.

Java Packing and unpacking a color

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.

To read a field: shift it down to the lowest bits, then mask with & 0xFF (eight ones) to drop everything above it. To write fields: shift each one up to its position and combine them with |. The same pattern decodes IP addresses, Unicode code points in UTF-8, and binary file headers.

Helper methods in Integer and Long

You rarely need to write bit-twiddling loops yourself. Integer and Long come with fast, well-tested helpers (many of them compiled to a single CPU instruction):

Java Integer bit helpers

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.

The power-of-two trick works because x - 1 flips the lowest 1-bit and all the zeros below it. If x has only one 1-bit, x & (x - 1) clears it and leaves 0. bitCount (also called population count) is useful whenever you store a set as bits and need its size.

For more than 64 flags, use java.util.BitSet, a growable bit array with methods like set, clear, get, and, or and cardinality.

You may see the "XOR swap" trick, a ^= b; b ^= a; a ^= b;, which swaps two variables without a temporary. It's a fun puzzle, but it's slower than a plain swap on modern hardware and breaks if both names refer to the same array element. Use a temporary variable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is 6 & 3?

    6 is 110 and 3 is 011. Only the middle bit is 1 in both, so the result is 010, which is 2.
  2. 2. What does ~7 evaluate to?

    In two's complement, flipping all bits gives -x - 1, so ~7 is -8.
  3. 3. Given int flags = 0b1011;, which statement turns OFF only the bit with value 2?

    ~2 has every bit set except the 2-bit, so AND-ing with it clears that bit and keeps the rest. &= 2 would clear every OTHER bit instead.
  4. 4. What does -16 >> 2 evaluate to?

    The signed right shift copies the sign bit, so it divides by 4 and keeps the number negative. The large positive number is what -16 >>> 2 would give.
  5. 5. What does 1 << 33 evaluate to for an int?

    For int, only the lowest 5 bits of the shift distance are used, so 33 becomes 1 and the result is 1 << 1 = 2. Use 1L << 33 for a long.

Summary

  • &, | and ^ combine integers bit by bit (AND, OR, XOR); ~ flips every bit. Operands smaller than int are promoted first.
  • Java stores negative integers in two's complement: -1 is all ones, ~x == -x - 1, and int has one more negative value than positive.
  • << shifts left (multiplies by powers of 2), >> shifts right keeping the sign (rounds down), >>> shifts right filling with zeros.
  • Shift distances are taken modulo 32 for int and 64 for long; use 1L << n for high bits.
  • Flags use |= to set, &= ~FLAG to clear, ^= to toggle and (flags & FLAG) != 0 to test, always with parentheses.
  • Shift-and-mask ((x >> 16) & 0xFF) extracts packed fields; Integer.bitCount, toBinaryString, numberOfTrailingZeros and friends do the common jobs for you.

Next: Operator Precedence and the Ternary Operator, which shows how Java decides what an expression with many operators means.