Skip to lesson

Every int and long in Java is stored in memory as a fixed-width row of 0s and 1s called bits (binary digits). Before you can use bitwise operators or bitmasks to speed up your algorithms, you need to read binary numbers as fluently as you read decimal numbers.

Base 2 and place values

A binary number is written using only 0 and 1, where each position is a power of 2; for example 1011 in binary is 11 in decimal.

In everyday decimal (base 10), each digit position from right to left represents a power of 10: 10⁰ = 1, 10¹ = 10, 10² = 100, and so on, so 305₁₀ = 3 × 100 + 0 × 10 + 5 × 1.

BinaryLiterals.javaJava
public class BinaryLiterals {    public static void main(String[] args) {        int x = 0b1101;         // 8 + 4 + 0 + 1        int mask = 0b1010_0101; // _ only helps you read it        System.out.println(x);        System.out.println(mask);        System.out.println(x % 2 == 1 ? "odd: LSB is 1" : "even: LSB is 0");    }}
Output
13
165
odd: LSB is 1

In binary (base 2), there are only two digits—0 and 1—and each bit position k (0-indexed from the right) represents a power of 2: 2⁰ = 1, 2¹ = 2, 2² = 4, 2³ = 8, 2⁴ = 16, 2⁵ = 32, 2⁶ = 64, 2⁷ = 128. For example, the 4-bit binary number 1101 equals 1 × 2³ + 1 × 2² + 0 × 2¹ + 1 × 2⁰ = 8 + 4 + 0 + 1 = 13.

The rightmost bit (bit 0, worth 2⁰ = 1) is called the least significant bit (LSB), and it alone determines whether a number is odd (LSB == 1) or even (LSB == 0). The leftmost bit is called the most significant bit (MSB).

  • Binary literals in Java: Prefix any binary number with 0b or 0B (and optional _ separators for readability), such as int x = 0b1101; (13) or int mask = 0b1010_0101; (165).
  • Memorize powers of 2 up to 2¹⁰: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 (and remember 2¹⁰ = 1024 ≈ 10³, 2²⁰ ≈ 10⁶, 2³⁰ ≈ 10⁹).

Converting between decimal and binary

To convert a binary string to decimal, start with val = 0 and scan bits from left to right: for each bit b, double the running value and add the bit (val = val * 2 + b).

  1. Handle n == 0: If n is 0, its binary representation is "0".
  2. Extract remainders: While n > 0, append n % 2 (0 or 1) to a StringBuilder and update n = n / 2.
  3. Reverse at the end: Because n % 2 extracts the rightmost bit first, call sb.reverse().toString() so the most significant bit comes first.

Example 1 · Converting Between Decimal and Binary by Hand and with Java Helpers

BinaryConversionDemo.javaJava
public class BinaryConversionDemo {    public static String decimalToBinary(int n) {        if (n == 0) return "0";        StringBuilder sb = new StringBuilder();        while (n > 0) {            sb.append(n % 2); // Remainder is the rightmost bit            n /= 2;           // Shift down by dividing by 2        }        return sb.reverse().toString();    }
    public static int binaryToDecimal(String bits) {        int result = 0;        for (int i = 0; i < bits.length(); i++) {            int bit = bits.charAt(i) - '0';            result = result * 2 + bit;        }        return result;    }
    public static void main(String[] args) {        int num = 0b101101; // Binary literal for 32 + 8 + 4 + 1 = 45        System.out.println("0b101101 in decimal:  " + num);        System.out.println("Manual toBinary(45):  " + decimalToBinary(45));        System.out.println("Built-in toBinary:    " + Integer.toBinaryString(45));        System.out.println("Manual toDecimal:     " + binaryToDecimal("101101"));        System.out.println("Integer.parseInt:     " + Integer.parseInt("101101", 2));    }}
Output
0b101101 in decimal:  45
Manual toBinary(45):  101101
Built-in toBinary:    101101
Manual toDecimal:     45
Integer.parseInt:     45

What this code does

  • decimalToBinary(45) extracts remainders 1, 0, 1, 1, 0, 1 as 45 -> 22 -> 11 -> 5 -> 2 -> 1 -> 0 and reverses them into "101101".
  • binaryToDecimal("101101") uses Horner's method (result = result * 2 + bit) to evaluate the powers of 2 in a single left-to-right pass in O(log n) time.

To convert a non-negative decimal integer n to binary, repeatedly divide n by 2: each remainder n % 2 gives the next binary digit from right to left (LSB first), and n = n / 2 shifts the remaining bits down until n reaches 0.

Integer.toBinaryString and Integer.parseInt

Integer.toBinaryString(n) turns an int into its binary digits, and Integer.parseInt(str, 2) reads binary digits back into an int. With these helpers in the Integer and Long wrapper classes, you rarely need to write the conversion loop in production code.

BinaryHelpers.javaJava
public class BinaryHelpers {    public static void main(String[] args) {        System.out.println(Integer.toBinaryString(13));        System.out.println(Integer.parseInt("1101", 2));        System.out.println(Integer.toBinaryString(-5).length()); // all 32 bits    }}
Output
1101
13
32
  • Integer.toBinaryString(n): Returns the unsigned binary string of a 32-bit int with leading '0' bits stripped (so Integer.toBinaryString(13) returns "1101").
  • Integer.parseInt(str, 2): Parses a binary string back into a signed int (for example, Integer.parseInt("1101", 2) returns 13).
Because Integer.toBinaryString(n) formats all 32 bits as unsigned, a positive number like 5 prints as "101" (3 characters), whereas a negative number like -5 has its leftmost bit set to 1 and prints all 32 characters!

Two's complement for negatives (simplified)

How does a 32-bit Java int store negative numbers without a separate minus sign? Java (and virtually all modern CPUs) uses two's complement representation.

Example 2 · Inspecting Two's Complement for Positive and Negative Integers

TwosComplementDemo.javaJava
public class TwosComplementDemo {    // Format an int as a full 32-bit binary string with spaces every 8 bits    public static String to32Bits(int x) {        String raw = String.format("%32s", Integer.toBinaryString(x)).replace(' ', '0');        return raw.substring(0, 8) + "_" + raw.substring(8, 16) + "_"             + raw.substring(16, 24) + "_" + raw.substring(24, 32);    }
    public static void main(String[] args) {        System.out.println(" 5:        " + to32Bits(5));        System.out.println("~5 (flip): " + to32Bits(~5) + " (value = " + (~5) + ")");        System.out.println("-5 (~5+1): " + to32Bits(-5) + " (value = " + (~5 + 1) + ")");        System.out.println("-1:        " + to32Bits(-1));        System.out.println("MAX_VALUE: " + to32Bits(Integer.MAX_VALUE));        System.out.println("MIN_VALUE: " + to32Bits(Integer.MIN_VALUE));    }}
Output
 5:        00000000_00000000_00000000_00000101
~5 (flip): 11111111_11111111_11111111_11111010 (value = -6)
-5 (~5+1): 11111111_11111111_11111111_11111011 (value = -5)
-1:        11111111_11111111_11111111_11111111
MAX_VALUE: 01111111_11111111_11111111_11111111
MIN_VALUE: 10000000_00000000_00000000_00000000

What this code does

  • Flipping all 32 bits of 5 (...00000101) gives ~5 (...11111010), which equals -6; adding 1 produces -5 (...11111011).
  • Because -x == ~x + 1, we always have ~x == -x - 1 for every Java int or long.

Example 3 · Binary Addition Carry Chain and Wrapping from MAX_VALUE to MIN_VALUE

BinaryAdditionDemo.javaJava
public class BinaryAdditionDemo {    public static String addBinaryStrings(String a, String b) {        StringBuilder sb = new StringBuilder();        int i = a.length() - 1;        int j = b.length() - 1;        int carry = 0;        while (i >= 0 || j >= 0 || carry > 0) {            int sum = carry;            if (i >= 0) sum += a.charAt(i--) - '0';            if (j >= 0) sum += b.charAt(j--) - '0';            sb.append(sum % 2); // Current bit is sum mod 2            carry = sum / 2;    // Carry into next column is sum / 2        }        return sb.reverse().toString();    }
    public static void main(String[] args) {        System.out.println("1011 + 1101 = " + addBinaryStrings("1011", "1101"));        int max = Integer.MAX_VALUE;        int wrapped = max + 1; // Carries into sign bit 31!        System.out.println("MAX_VALUE + 1 = " + wrapped + " (equals MIN_VALUE: "                + (wrapped == Integer.MIN_VALUE) + ")");    }}
Output
1011 + 1101 = 11000
MAX_VALUE + 1 = -2147483648 (equals MIN_VALUE: true)

What this code does

  • Adding 1011 (11) and 1101 (13) column by column from right to left propagates carries just like decimal addition (1 + 1 = 0 with carry = 1), yielding 11000 (24).
  • Adding 1 to Integer.MAX_VALUE (0111...111) carries all the way into bit 31, producing 1000...000, which is Integer.MIN_VALUE (-2147483648).

In this simplified mental model, the leftmost bit (bit 31 of an int) acts as a negative place value of -2³¹, while the remaining 31 bits (30 down to 0) add their usual positive powers of 2.

This leads to three facts you will use constantly:

  • -1 is all 1s: In 32-bit two's complement, -1 is 11111111_11111111_11111111_11111111 (32 ones), because -2³¹ + (2³¹ - 1) = -1.
  • How to negate any int x: Flip every bit (~x, where 0 becomes 1 and 1 becomes 0) and add 1: -x == ~x + 1.
  • Range of a 32-bit int: Integer.MAX_VALUE is 0111...111 (2³¹ - 1 = 2,147,483,647) and Integer.MIN_VALUE is 1000...000 (-2³¹ = -2,147,483,648). Because 0 uses the pattern 0000...000, there is one more negative number than positive!

Predict the output

Predict the output

Read each program and pick what it prints.

Round 1 of 3

Flip every bit of 5.

public class NotDemo {
public static void main(String[] args) {
int x = 5;
System.out.println(~x);
}
}

Next step

Check your understanding

10 quick questions