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 int is 32 bits and a long is 64. Positive numbers are ordinary binary: 5 is 101. Negative numbers use two's complement: the highest bit is the sign bit, and -x is stored as "invert all bits of x, then add 1". This system lets the CPU use the same addition circuit for positive and negative numbers, and it is the reason for several results on this page, such as ~5 being -6.

The bitwise and shift operators
OperatorNameResult bit is 1 when...Typical use
a & bANDBoth bits are 1Testing or clearing bits, masking
a | bORAt least one bit is 1Setting bits, combining flags
a ^ bXOR (exclusive or)The bits differToggling bits, hashing, checksums
~aNOT (complement)The bit was 0Building a mask to clear bits
a << nLeft shiftBits move left; zeros come in on the rightMultiply by 2n, build masks
a >> nSigned right shiftBits move right; copies of the sign bit come in on the leftDivide by 2n (rounding down)
a >>> nUnsigned right shiftBits move right; zeros come in on the leftTreating 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.

Java
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:

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, ~x + 1 gave -x. It follows that ~x is always -x - 1, so ~0 is -1, which is all 32 bits set.
  • In 8 bits, -128 is 10000000. Its "negation" is itself, which is why a byte runs from -128 to 127 and why Math.abs(Integer.MIN_VALUE) is negative.
  • The bits 11110000 mean -16 as a signed byte and 240 as an unsigned one. Java has no unsigned integer types, but Byte.toUnsignedInt, Integer.toUnsignedString, Integer.compareUnsigned and divideUnsigned (Java 8 and later) treat the same bits as unsigned when you need to.

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.

Java
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:

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.
  • ~a flips all 32 bits, not just the 8 shown, so the full value is -203, which is -202 - 1.
  • a << 1 doubled 202 to 404, which no longer fits in 8 bits; the int keeps it. a >> 2 divided by 4 and dropped the remainder: 202 / 4 = 50.
  • XOR has a useful property: x ^ k ^ k gives back x. It is the basis of simple checksums, parity bits and many hash functions.

Shifts: signed, unsigned and the shift distance

Shifting a positive number right works the same with >> and >>>. The difference only appears with negative numbers, so the program uses -16 and prints all 32 bits.

Java
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:

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
  • -16 >> 2 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 >>> when the bits are data rather than a signed number, such as hash codes or packed fields.
  • >> rounds toward negative infinity, so -7 >> 1 is -4 while -7 / 2 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.
  • For an int, only the low 5 bits of the shift distance are used (6 bits for a long), so 1 << 32 is 1, not 0. To build a 64-bit mask, the left operand must be a long: 1L << 32.

Flags: many booleans in one int

Each bit of an int can stand for one yes/no option. This is how file permissions, modifier flags in java.lang.reflect.Modifier and many protocol headers are stored. The program defines four permission flags, one per bit, then sets, clears, toggles and tests them, and finishes with some classic one-line tests.

Java
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:

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)
Flag operations
OperationCode
Combine flagsREAD | WRITE
Turn a flag onperms |= EXEC
Turn a flag offperms &= ~WRITE
Toggle a flagperms ^= ADMIN
Test a flag(perms & READ) != 0
  • (n & 1) == 0 tests for an even number by looking at the lowest bit.
  • (n & (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 101000, so it is not a power of two.
  • In Java code, prefer EnumSet 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.

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 int, as java.awt.Color and Android do, then decodes the four bytes of an IPv4 address, which shows the most common bitwise bug in Java: forgetting that byte is signed.

Java
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:

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: 0xFFFFA500 is alpha 255, red 255, green 165 (A5) and blue 0. Unpacking shifts the component down and masks with 0xFF to keep only 8 bits.
  • Alpha sits in the top 8 bits, including the sign bit. >> 24 spread that sign and gave -1; >>> 24 gave the correct 255.
  • The bytes 192, 168 and 254 do not fit in a signed byte, so Java stores them as -64, -88 and -2. Whenever bytes come from a file, a socket or a hash, mask them with & 0xFF to get 0 to 255.
  • 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

Integer and Long have methods for the common bit tricks. They are clearer than hand-written loops and, for methods like bitCount and numberOfLeadingZeros, the JIT compiler replaces them with single CPU instructions. The program applies them to 360, which is 101101000 in binary and so has set bits in several places.

Java
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:

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).
  • reverse mirrors all 32 bits, so the low bits of 360 end up at the top.
  • Rounding a size up to the next power of two, as HashMap does for its table, takes one highestOneBit call: 17 becomes 32 and 1,000 becomes 1,024. Powers of two let a hash table pick a bucket with hash & (size - 1) instead of a slower %; see HashMap internals.
  • For a power of two, 31 - numberOfLeadingZeros(n) is its base-2 logarithm, computed without floating point.

Boolean operators, precedence and BitSet

&, | and ^ also work on boolean values, which is a source of subtle bugs. The program counts how many times each side of a condition runs, shows a precedence surprise, and then uses java.util.BitSet to find all primes below one million with a sieve, one bit per number.

Java
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:

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 false (1 call); & evaluated both sides (2 calls). Code such as obj != null & obj.isValid() therefore throws NullPointerException; use && and || for conditions.
  • Arithmetic operators bind tighter than shifts, so 1 + 2 << 1 is (1 + 2) << 1 = 6. Comparison binds tighter than &, so x & 1 == 1 means x & (1 == 1) and does not compile. Parenthesize bitwise expressions.
  • The sieve found 78,498 primes below 1,000,000, which is the known count. The BitSet used about 125 KB, one bit per number, where a boolean[] uses a whole byte per element, about 1 MB.

When to use bitwise operations

Typical uses and alternatives
TaskBitwise approachOften better in plain Java code
A set of optionsint flags with | and &EnumSet
A large set of small integersBits in a long[]BitSet
Reading binary formats and protocolsShifts and & 0xFFByteBuffer with an explicit byte order
Multiply or divide by 2n<<, >>* and /; the JIT optimizes them
Count bits, find the highest bitLoopsInteger.bitCount, highestOneBit
Unsigned values>>>, masksInteger.toUnsignedLong, compareUnsigned

For the integer types themselves, see data types; for reading binary data, see ByteBuffer.