Reading history

Java Bit Manipulation

6 min read 0 views

Use Java's bitwise operators AND, OR, XOR, NOT and shifts, store flags in one int, and learn classic bit tricks with clear binary examples.

Inside the computer, every int is 32 bits. Java’s bitwise operators let you work on those bits directly. That sounds low-level, but it is everywhere: file permissions, feature flags, fast checks for even numbers and powers of two, compact storage of many true/false values, and some favourite coding-interview puzzles. This lesson explains each operator with binary pictures and then shows the most useful tricks.

In this lesson you will learn

  • AND &, OR |, XOR ^ and NOT ~
  • Shifts: <<, >> and >>>
  • Storing several flags in one int
  • Tricks: odd/even, power of two, single number with XOR
  • Generating all subsets with bit masks

You should know Java operators and binary numbers from number systems.

The Bitwise Operators

public class Main {
    static String bin(int x) {
        return String.format("%8s", Integer.toBinaryString(x & 0xFF)).replace(' ', '0');
    }

    public static void main(String[] args) {
        int a = 12, b = 10;   // 00001100 and 00001010
        System.out.println("a      = " + bin(a) + " (" + a + ")");
        System.out.println("b      = " + bin(b) + " (" + b + ")");
        System.out.println("a & b  = " + bin(a & b) + " (" + (a & b) + ")   AND: 1 where both are 1");
        System.out.println("a | b  = " + bin(a | b) + " (" + (a | b) + ")  OR: 1 where either is 1");
        System.out.println("a ^ b  = " + bin(a ^ b) + " (" + (a ^ b) + ")   XOR: 1 where they differ");
        System.out.println("~a     = " + (~a) + "  (NOT flips every bit; -(a+1))");
        System.out.println("a << 2 = " + bin(a << 2) + " (" + (a << 2) + ")  shift left = multiply by 4");
        System.out.println("a >> 2 = " + bin(a >> 2) + " (" + (a >> 2) + ")   shift right = divide by 4");

        int neg = -16;
        System.out.println("-16 >> 2  = " + (neg >> 2) + "  (keeps the sign)");
        System.out.println("-16 >>> 28 = " + (neg >>> 28) + "  (fills with zeros)");

        System.out.println("Binary literal 0b1010_1010 = " + 0b1010_1010);
        System.out.println("bitCount(255) = " + Integer.bitCount(255)
            + ", highestOneBit(100) = " + Integer.highestOneBit(100));
    }
}

Output

a      = 00001100 (12)
b      = 00001010 (10)
a & b  = 00001000 (8)   AND: 1 where both are 1
a | b  = 00001110 (14)  OR: 1 where either is 1
a ^ b  = 00000110 (6)   XOR: 1 where they differ
~a     = -13  (NOT flips every bit; -(a+1))
a << 2 = 00110000 (48)  shift left = multiply by 4
a >> 2 = 00000011 (3)   shift right = divide by 4
-16 >> 2  = -4  (keeps the sign)
-16 >>> 28 = 15  (fills with zeros)
Binary literal 0b1010_1010 = 170
bitCount(255) = 8, highestOneBit(100) = 64
OperatorRule for each bit12 op 10
& AND1 only if both bits are 18
| OR1 if either bit is 114
^ XOR1 if the bits differ6
~ NOTFlips every bit~12 = −13
  • ~a equals -(a + 1) because Java stores negative numbers in two’s complement.
  • a << n moves bits left, multiplying by 2ⁿ: 12 << 2 = 48.
  • a >> n moves bits right, dividing by 2ⁿ and keeping the sign: −16 >> 2 = −4.
  • >>> shifts right and fills with zeros, so a negative number becomes a large positive one.
  • 0b starts a binary literal; underscores make long numbers easier to read.

Flags and Tricks

public class Main {
    // Permission flags packed into one int
    static final int READ = 1, WRITE = 2, EXECUTE = 4;   // 001, 010, 100

    static String describe(int p) {
        return ((p & READ) != 0 ? "r" : "-") + ((p & WRITE) != 0 ? "w" : "-") + ((p & EXECUTE) != 0 ? "x" : "-");
    }

    static boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; }

    public static void main(String[] args) {
        int perm = READ | WRITE;                  // set two flags
        System.out.println("start      : " + describe(perm));
        perm |= EXECUTE;                          // turn a flag on
        System.out.println("add x      : " + describe(perm));
        perm &= ~WRITE;                           // turn a flag off
        System.out.println("remove w   : " + describe(perm));
        perm ^= READ;                             // toggle a flag
        System.out.println("toggle r   : " + describe(perm));

        // Classic tricks
        for (int n : new int[]{7, 8, 7 & 6, 1024}) {
            System.out.println(n + (n % 2 == 0 ? " even" : " odd") + ", odd by bit test: " + ((n & 1) == 1)
                + ", power of two: " + isPowerOfTwo(n));
        }

        // XOR finds the one number that appears once
        int[] nums = {4, 7, 2, 7, 4};
        int single = 0;
        for (int x : nums) single ^= x;
        System.out.println("Appears once: " + single);

        // Every subset of {A, B, C} using the bits of 0..7
        char[] items = {'A', 'B', 'C'};
        StringBuilder all = new StringBuilder();
        for (int mask = 0; mask < (1 << items.length); mask++) {
            StringBuilder s = new StringBuilder("{");
            for (int i = 0; i < items.length; i++) if ((mask & (1 << i)) != 0) s.append(items[i]);
            all.append(s).append("} ");
        }
        System.out.println(all.toString().trim());
    }
}

Output

start      : rw-
add x      : rwx
remove w   : r-x
toggle r   : --x
7 odd, odd by bit test: true, power of two: false
8 even, odd by bit test: false, power of two: true
6 even, odd by bit test: false, power of two: false
1024 even, odd by bit test: false, power of two: true
Appears once: 2
{} {A} {B} {AB} {C} {AC} {BC} {ABC}
TaskCode
Turn a flag onp |= FLAG
Turn a flag offp &= ~FLAG
Toggle a flagp ^= FLAG
Test a flag(p & FLAG) != 0
Is n odd?(n & 1) == 1
Is n a power of two?n > 0 && (n & (n - 1)) == 0
  • Each flag is a different power of two, so it owns one bit. One int can hold 32 flags; Linux file permissions such as 755 work this way.
  • A power of two has exactly one 1 bit. Subtracting 1 turns that bit off and all lower bits on, so the AND is 0. For 8: 1000 & 0111 = 0.
  • XOR of a number with itself is 0, and XOR with 0 changes nothing. XOR-ing every value cancels the pairs, leaving the single 2.
  • The numbers 0 to 7 have every possible pattern of 3 bits. Treating bit i as “include item i” lists all 8 subsets.

Common Mistakes

  1. Confusing & with &&. && is logical and short-circuits; & on ints works bit by bit.
  2. Operator precedence. p & FLAG != 0 is parsed as p & (FLAG != 0) and does not compile; add brackets.
  3. Shifting by 32 or more. For an int, Java uses only the lowest 5 bits of the shift amount, so 1 << 32 is 1.
  4. Using >> when you want an unsigned result; use >>>.

Practice Exercises

Exercise 1. What is 5 & 3, 5 | 3 and 5 ^ 3?

Show answer

5 = 101 and 3 = 011. AND = 001 = 1, OR = 111 = 7, XOR = 110 = 6.

Exercise 2. Swap two ints x = 9 and y = 4 using XOR and no temporary variable.

Show answer
int x = 9, y = 4;
x ^= y;   // x = 9 ^ 4
y ^= x;   // y = 4 ^ (9 ^ 4) = 9
x ^= y;   // x = (9 ^ 4) ^ 9 = 4
System.out.println(x + " " + y);   // 4 9

It is a neat trick, but a temporary variable is clearer in real code.

Frequently Asked Questions

Is n & 1 faster than n % 2?

Modern compilers usually turn both into the same fast instruction, so write whichever is clearer. Note that n % 2 is −1 for negative odd numbers, while n & 1 is 1.

Is there a class for large sets of flags?

Yes. java.util.BitSet stores any number of bits and has methods such as set, clear, get and cardinality. For flags based on an enum, EnumSet is clearer still.

Summary

  • &, |, ^, ~ work on each bit; shifts move bits left or right.
  • Use one bit per flag: set with |=, clear with &= ~, test with &.
  • n & (n − 1) clears the lowest set bit; XOR cancels pairs.
  • Masks from 0 to 2ⁿ − 1 list every subset of n items.

Next: Java Project: Bank Account System.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *