Binary numbers
28 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
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"); }}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
0bor0B(and optional_separators for readability), such asint x = 0b1101;(13) orint 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).
- Handle
n == 0: If n is0, its binary representation is"0". - Extract remainders: While
n > 0, appendn % 2(0or1) to aStringBuilderand updaten = n / 2. - Reverse at the end: Because
n % 2extracts the rightmost bit first, callsb.reverse().toString()so the most significant bit comes first.
Example 1 · Converting Between Decimal and Binary by Hand and with Java Helpers
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)); }}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 remainders1, 0, 1, 1, 0, 1as45 -> 22 -> 11 -> 5 -> 2 -> 1 -> 0and 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.
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 }}1101 13 32
Integer.toBinaryString(n): Returns the unsigned binary string of a 32-bitintwith leading'0'bits stripped (soInteger.toBinaryString(13)returns"1101").Integer.parseInt(str, 2): Parses a binary string back into a signedint(for example,Integer.parseInt("1101", 2)returns13).
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
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)); }}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; adding1produces-5(...11111011). - Because
-x == ~x + 1, we always have~x == -x - 1for every Javaintorlong.
Example 3 · Binary Addition Carry Chain and Wrapping from MAX_VALUE to MIN_VALUE
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) + ")"); }}1011 + 1101 = 11000 MAX_VALUE + 1 = -2147483648 (equals MIN_VALUE: true)
What this code does
- Adding
1011(11) and1101(13) column by column from right to left propagates carries just like decimal addition (1 + 1 = 0withcarry = 1), yielding11000(24). - Adding
1toInteger.MAX_VALUE(0111...111) carries all the way into bit31, producing1000...000, which isInteger.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:
-1is all1s: In 32-bit two's complement,-1is11111111_11111111_11111111_11111111(32 ones), because -2³¹ + (2³¹ - 1) = -1.- How to negate any
intx: Flip every bit (~x, where0becomes1and1becomes0) and add1:-x == ~x + 1. - Range of a 32-bit
int:Integer.MAX_VALUEis0111...111(2³¹ - 1 = 2,147,483,647) andInteger.MIN_VALUEis1000...000(-2³¹ = -2,147,483,648). Because0uses the pattern0000...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.
Next step
Check your understanding
10 quick questions