Bitwise Operators in Java
Bitwise operators work on the individual bits of an integer. They are how flags are packed into one number, how colors and network addresses are encoded, and how hash tables and compression code run fast. This page explains how Java stores integers in binary first, then shows each operator, shifts, real uses such as flags and packed colors, the signed-byte trap, and the library methods that do the bit tricks for you.
Contents
How Java stores integers in binary
An intlong101~5
| Operator | Name | Result bit is 1 when... | Typical use |
|---|---|---|---|
a & b | AND | Both bits are 1 | Testing or clearing bits, masking |
a | b | OR | At least one bit is 1 | Setting bits, combining flags |
a ^ b | XOR (exclusive or) | The bits differ | Toggling bits, hashing, checksums |
~a | NOT (complement) | The bit was 0 | Building a mask to clear bits |
a << n | Left shift | Bits move left; zeros come in on the right | Multiply by 2n, build masks |
a >> n | Signed right shift | Bits move right; copies of the sign bit come in on the left | Divide by 2n (rounding down) |
a >>> n | Unsigned right shift | Bits move right; zeros come in on the left | Treating the bits as unsigned |
The program below shows two's complement directly: the bits of a few numbers, their complement, and the complement plus one.
public class TwosComplement {
static String bits8(int n) {
return String.format("%8s", Integer.toBinaryString(n & 0xFF)).replace(' ', '0');
}
public static void main(String[] args) {
// In two's complement, -x is ~x + 1: invert every bit, then add one
for (int x : new int[] {1, 5, 127}) {
System.out.printf("%4d = %s ~%d = %s ~%d + 1 = %s = %d%n",
x, bits8(x), x, bits8(~x), x, bits8(~x + 1), (byte) (~x + 1));
}
System.out.println("-128 = " + bits8(-128) + " (the byte with no positive partner)");
System.out.println("~0 = " + ~0 + ", so ~x == -x - 1 for every int");
// The same bits read as signed or unsigned
byte b = (byte) 0b1111_0000;
System.out.println("byte 11110000 signed = " + b + ", unsigned = " + Byte.toUnsignedInt(b));
int big = 0xFFFF_FFFF;
System.out.println("int 0xFFFFFFFF signed = " + big
+ ", unsigned = " + Integer.toUnsignedString(big));
System.out.println("compareUnsigned(-1, 1) = " + Integer.compareUnsigned(-1, 1));
}
}
Output:
1 = 00000001 ~1 = 11111110 ~1 + 1 = 11111111 = -1
5 = 00000101 ~5 = 11111010 ~5 + 1 = 11111011 = -5
127 = 01111111 ~127 = 10000000 ~127 + 1 = 10000001 = -127
-128 = 10000000 (the byte with no positive partner)
~0 = -1, so ~x == -x - 1 for every int
byte 11110000 signed = -16, unsigned = 240
int 0xFFFFFFFF signed = -1, unsigned = 4294967295
compareUnsigned(-1, 1) = 1
- For every value,
gave~x + 1 . It follows that-x is always~x , so-x - 1 is -1, which is all 32 bits set.~0 - In 8 bits, -128 is
. Its "negation" is itself, which is why a10000000 runs from -128 to 127 and whybyte is negative.Math.abs(Integer.MIN_VALUE) - The bits
mean -16 as a signed11110000 and 240 as an unsigned one. Java has no unsigned integer types, butbyte ,Byte.toUnsignedInt ,Integer.toUnsignedString andInteger.compareUnsigned (Java 8 and later) treat the same bits as unsigned when you need to.divideUnsigned
AND, OR, XOR and NOT
The program applies each operator to two 8-bit patterns chosen so that every combination of bits (0 and 0, 0 and 1, 1 and 0, 1 and 1) appears in some column, and prints the result in binary and decimal.
public class BitOps {
// Show the low 8 bits so each operation is easy to follow
static String bits(int n) {
return String.format("%8s", Integer.toBinaryString(n & 0xFF)).replace(' ', '0');
}
public static void main(String[] args) {
int a = 0b1100_1010; // 202
int b = 0b1010_0110; // 166
System.out.println("a = " + bits(a) + " (" + a + ")");
System.out.println("b = " + bits(b) + " (" + b + ")");
System.out.println("a & b = " + bits(a & b) + " (" + (a & b) + ")");
System.out.println("a | b = " + bits(a | b) + " (" + (a | b) + ")");
System.out.println("a ^ b = " + bits(a ^ b) + " (" + (a ^ b) + ")");
System.out.println("~a = " + bits(~a) + " (low 8 bits of " + ~a + ")");
System.out.println("a << 1 = " + bits(a << 1) + " (low 8 bits of " + (a << 1) + ")");
System.out.println("a >> 2 = " + bits(a >> 2) + " (" + (a >> 2) + ")");
}
}
Output:
a = 11001010 (202)
b = 10100110 (166)
a & b = 10000010 (130)
a | b = 11101110 (238)
a ^ b = 01101100 (108)
~a = 00110101 (low 8 bits of -203)
a << 1 = 10010100 (low 8 bits of 404)
a >> 2 = 00110010 (50)
- Read each result column by column:
keeps a 1 only where both inputs have one,& where either has one, and| where exactly one has one.^ flips all 32 bits, not just the 8 shown, so the full value is -203, which is -202 - 1.~a doubled 202 to 404, which no longer fits in 8 bits; thea << 1 keeps it.int divided by 4 and dropped the remainder: 202 / 4 = 50.a >> 2- XOR has a useful property:
gives backx ^ k ^ k . It is the basis of simple checksums, parity bits and many hash functions.x
Shifts: signed, unsigned and the shift distance
Shifting a positive number right works the same with >>>>>
public class Shifts {
static String bits32(int n) {
return String.format("%32s", Integer.toBinaryString(n)).replace(' ', '0');
}
public static void main(String[] args) {
int neg = -16;
System.out.println("-16 " + bits32(neg));
System.out.println("-16 >> 2 " + bits32(neg >> 2) + " = " + (neg >> 2));
System.out.println("-16 >>> 2 " + bits32(neg >>> 2) + " = " + (neg >>> 2));
// Shifts multiply and divide by powers of two
System.out.println("5 << 3 = " + (5 << 3) + " (5 * 8)");
System.out.println("100 >> 2 = " + (100 >> 2) + " (100 / 4)");
System.out.println("-7 >> 1 = " + (-7 >> 1) + ", but -7 / 2 = " + (-7 / 2));
// The shift distance is taken modulo 32 for int
System.out.println("1 << 32 = " + (1 << 32) + ", 1 << 33 = " + (1 << 33));
System.out.println("1L << 32 = " + (1L << 32));
}
}
Output:
-16 11111111111111111111111111110000
-16 >> 2 11111111111111111111111111111100 = -4
-16 >>> 2 00111111111111111111111111111100 = 1073741820
5 << 3 = 40 (5 * 8)
100 >> 2 = 25 (100 / 4)
-7 >> 1 = -4, but -7 / 2 = -3
1 << 32 = 1, 1 << 33 = 2
1L << 32 = 4294967296
filled the left with 1s (copies of the sign bit) and gave -4: an arithmetic shift, which divides by 4 and keeps the sign.-16 >> 2 filled the left with 0s and gave 1,073,741,820: the bits read as a large positive number. Use-16 >>> 2 when the bits are data rather than a signed number, such as hash codes or packed fields.>>> rounds toward negative infinity, so>> is -4 while-7 >> 1 is -3. Replacing a division by a shift is only equivalent for non-negative numbers, and the JIT compiler already does this optimization where it is safe.-7 / 2- For an
, only the low 5 bits of the shift distance are used (6 bits for aint ), solong is 1, not 0. To build a 64-bit mask, the left operand must be a1 << 32 :long .1L << 32
Flags: many booleans in one int
Each bit of an intjava.lang.reflect.Modifier
public class Flags {
static final int READ = 1; // 0001
static final int WRITE = 1 << 1; // 0010
static final int EXEC = 1 << 2; // 0100
static final int ADMIN = 1 << 3; // 1000
static String describe(int perms) {
StringBuilder sb = new StringBuilder();
sb.append((perms & READ) != 0 ? 'r' : '-');
sb.append((perms & WRITE) != 0 ? 'w' : '-');
sb.append((perms & EXEC) != 0 ? 'x' : '-');
sb.append((perms & ADMIN) != 0 ? 'A' : '-');
return sb.toString();
}
public static void main(String[] args) {
int perms = READ | WRITE; // set two flags
System.out.println("start: " + describe(perms));
perms |= EXEC; // turn a flag on
System.out.println("add exec: " + describe(perms));
perms &= ~WRITE; // turn a flag off
System.out.println("remove write: " + describe(perms));
perms ^= ADMIN; // toggle a flag
System.out.println("toggle admin: " + describe(perms));
System.out.println("has read? " + ((perms & READ) != 0));
// Classic tricks
int n = 40;
System.out.println("40 is even: " + ((n & 1) == 0));
System.out.println("40 is a power of two: " + (n > 0 && (n & (n - 1)) == 0));
System.out.println("set bits in 40: " + Integer.bitCount(n));
System.out.println("lowest set bit of 40: " + Integer.lowestOneBit(n));
System.out.println("0xFF & (byte) -1: " + (0xFF & (byte) -1) + " (byte as unsigned)");
}
}
Output:
start: rw--
add exec: rwx-
remove write: r-x-
toggle admin: r-xA
has read? true
40 is even: true
40 is a power of two: false
set bits in 40: 2
lowest set bit of 40: 8
0xFF & (byte) -1: 255 (byte as unsigned)
| Operation | Code |
|---|---|
| Combine flags | READ | WRITE |
| Turn a flag on | perms |= EXEC |
| Turn a flag off | perms &= ~WRITE |
| Toggle a flag | perms ^= ADMIN |
| Test a flag | (perms & READ) != 0 |
tests for an even number by looking at the lowest bit.(n & 1) == 0 is true only for powers of two: subtracting 1 flips the lowest set bit and everything below it, so the AND is zero exactly when there was only one set bit. 40 is(n & (n - 1)) == 0 , so it is not a power of two.101000- In Java code, prefer
over hand-made int flags for options inside your own program: it is stored as a bit field internally but is type-safe and readable. Use int flags where the format is fixed by something outside, such as a file format or a protocol.EnumSet
Packing values: colors, bytes and network addresses
Shifts and masks put several small values into one larger one and take them out again. The program packs a color into one intjava.awt.Colorbyte
public class PackingBits {
// An ARGB color: 8 bits each of alpha, red, green and blue in one int
static int argb(int a, int r, int g, int b) {
return (a << 24) | (r << 16) | (g << 8) | b;
}
public static void main(String[] args) {
int orange = argb(255, 255, 165, 0);
System.out.printf("packed: 0x%08X%n", orange);
int red = (orange >> 16) & 0xFF;
int green = (orange >> 8) & 0xFF;
int blue = orange & 0xFF;
int alpha = orange >>> 24; // >>> so the sign bit does not spread
System.out.println("unpacked: a=" + alpha + " r=" + red + " g=" + green + " b=" + blue);
System.out.println("with >> instead of >>>: alpha = " + (orange >> 24));
// Bytes from a file or socket are signed in Java: mask with 0xFF to read 0..255
byte[] ip = {(byte) 192, (byte) 168, 1, (byte) 254};
System.out.println("bytes as Java sees them: " + ip[0] + "." + ip[1] + "." + ip[2]
+ "." + ip[3]);
System.out.println("masked with 0xFF: " + (ip[0] & 0xFF) + "." + (ip[1] & 0xFF)
+ "." + (ip[2] & 0xFF) + "." + (ip[3] & 0xFF));
// Four bytes into one int (big-endian, as in network protocols)
int address = (ip[0] & 0xFF) << 24 | (ip[1] & 0xFF) << 16 | (ip[2] & 0xFF) << 8
| (ip[3] & 0xFF);
System.out.println("as one int: " + Integer.toUnsignedString(address)
+ "; without masking: " + (ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3]));
}
}
Output:
packed: 0xFFFFA500
unpacked: a=255 r=255 g=165 b=0
with >> instead of >>>: alpha = -1
bytes as Java sees them: -64.-88.1.-2
masked with 0xFF: 192.168.1.254
as one int: 3232236030; without masking: -2
- Packing shifts each component to its position and ORs them together:
is alpha 255, red 255, green 165 (A5) and blue 0. Unpacking shifts the component down and masks with0xFFFFA500 to keep only 8 bits.0xFF - Alpha sits in the top 8 bits, including the sign bit.
spread that sign and gave -1;>> 24 gave the correct 255.>>> 24 - The bytes 192, 168 and 254 do not fit in a signed
, so Java stores them as -64, -88 and -2. Whenever bytes come from a file, a socket or a hash, mask them withbyte to get 0 to 255.& 0xFF - Combining the bytes without masking gave -2: each negative byte is sign-extended to 32 bits of 1s before the shift, and those 1s overwrite the other bytes in the OR.
Library methods for bit manipulation
IntegerLongbitCountnumberOfLeadingZeros101101000
public class IntegerBitMethods {
public static void main(String[] args) {
int n = 0b0000_0000_0000_0000_0000_0001_0110_1000; // 360
System.out.println("n = " + n + " = " + Integer.toBinaryString(n));
System.out.println("bitCount " + Integer.bitCount(n));
System.out.println("highestOneBit " + Integer.highestOneBit(n));
System.out.println("lowestOneBit " + Integer.lowestOneBit(n));
System.out.println("numberOfLeadingZeros " + Integer.numberOfLeadingZeros(n));
System.out.println("numberOfTrailingZeros " + Integer.numberOfTrailingZeros(n));
System.out.println("reverse " + Integer.toBinaryString(Integer.reverse(n)));
System.out.println("toHexString " + Integer.toHexString(n));
System.out.println("parseInt(\"101\", 2) " + Integer.parseInt("101", 2));
// Next power of two at or above a size, as hash tables size their arrays
for (int size : new int[] {1, 5, 16, 17, 1000}) {
int next = size <= 1 ? 1 : Integer.highestOneBit(size - 1) << 1;
System.out.print(size + " -> " + next + " ");
}
System.out.println();
// log2 of a power of two, without floating point
System.out.println("log2(1024) = " + (31 - Integer.numberOfLeadingZeros(1024)));
}
}
Output:
n = 360 = 101101000
bitCount 4
highestOneBit 256
lowestOneBit 8
numberOfLeadingZeros 23
numberOfTrailingZeros 3
reverse 10110100000000000000000000000
toHexString 168
parseInt("101", 2) 5
1 -> 1 5 -> 8 16 -> 16 17 -> 32 1000 -> 1024
log2(1024) = 10
- 360 has 4 set bits; its highest is 256 (28) and its lowest is 8 (23), which matches the 3 trailing zeros and the 23 leading zeros (32 - 9 digits).
mirrors all 32 bits, so the low bits of 360 end up at the top.reverse- Rounding a size up to the next power of two, as
does for its table, takes oneHashMap call: 17 becomes 32 and 1,000 becomes 1,024. Powers of two let a hash table pick a bucket withhighestOneBit instead of a slowerhash & (size - 1) ; see%HashMap internals . - For a power of two,
is its base-2 logarithm, computed without floating point.31 - numberOfLeadingZeros(n)
Boolean operators, precedence and BitSet
&|^booleanjava.util.BitSet
import java.util.BitSet;
public class BitSetAndBoolean {
static int calls;
static boolean check(boolean result) {
calls++;
return result;
}
public static void main(String[] args) {
// & and | on booleans evaluate both sides; && and || stop early
calls = 0;
boolean r1 = check(false) && check(true);
System.out.println("false && x: " + r1 + ", calls = " + calls);
calls = 0;
boolean r2 = check(false) & check(true);
System.out.println("false & x: " + r2 + ", calls = " + calls);
System.out.println("true ^ true = " + (true ^ true) + " (exclusive or)");
// Precedence: shifts bind tighter than &, but + binds tighter than <<
int x = 3;
System.out.println("1 + 2 << 1 = " + (1 + 2 << 1) + ", 1 + (2 << 1) = " + (1 + (2 << 1)));
System.out.println("(x & 1) == 1: " + ((x & 1) == 1));
// BitSet: a growable array of bits, here a sieve of Eratosthenes up to 1,000,000
int limit = 1000000;
BitSet composite = new BitSet(limit + 1);
for (int i = 2; (long) i * i <= limit; i++) {
if (!composite.get(i)) {
for (int j = i * i; j <= limit; j += i) {
composite.set(j);
}
}
}
int primes = limit - 1 - composite.cardinality();
System.out.println("primes below 1,000,000: " + primes);
System.out.println("BitSet memory: " + composite.size() / 8 + " bytes; a boolean[] of the"
+ " same length uses about " + (limit + 1) + " bytes");
}
}
Output:
false && x: false, calls = 1
false & x: false, calls = 2
true ^ true = false (exclusive or)
1 + 2 << 1 = 6, 1 + (2 << 1) = 5
(x & 1) == 1: true
primes below 1,000,000: 78498
BitSet memory: 125008 bytes; a boolean[] of the same length uses about 1000001 bytes
stopped after the left side was&& (1 call);false evaluated both sides (2 calls). Code such as& therefore throwsobj != null & obj.isValid() ; useNullPointerException and&& for conditions.||- Arithmetic operators bind tighter than shifts, so
is1 + 2 << 1 = 6. Comparison binds tighter than(1 + 2) << 1 , so& meansx & 1 == 1 and does not compile. Parenthesize bitwise expressions.x & (1 == 1) - The sieve found 78,498 primes below 1,000,000, which is the known count. The
used about 125 KB, one bit per number, where aBitSet uses a whole byte per element, about 1 MB.boolean[]
When to use bitwise operations
| Task | Bitwise approach | Often better in plain Java code |
|---|---|---|
| A set of options | int|& | EnumSet |
| A large set of small integers | Bits in a long[] | BitSet |
| Reading binary formats and protocols | Shifts and & 0xFF | ByteBuffer |
| Multiply or divide by 2n | <<>> | */ |
| Count bits, find the highest bit | Loops | Integer.bitCounthighestOneBit |
| Unsigned values | >>> | Integer.toUnsignedLongcompareUnsigned |
For the integer types themselves, see