Convert Binary to Decimal in Java

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
Base conversion

What you’ll learn

  • How positional notation turns a binary bit pattern into a decimal integer.
  • Two Java styles: digit peel (integer that looks like 101010) and Horner on a String.
  • Why integer powers beat Math.pow here, how to validate digits, and a browser live preview.

Overview

Binary uses powers of two from the rightmost bit (least significant). This page shows the same math two ways in Java: peel digits from a “binary-looking” integer, or scan a string of '0' and '1' characters with Horner’s rule.

Two programs

Digit peel (integer input) plus string Horner.

Live preview

Type a bit string; see decimal via parseInt(..., 2) for a quick check.

Fixes vs naive Math.pow

Exact integer weights, digit checks, and long where helpful.

Prerequisites

Loops, integer division and modulo, String basics, and the idea of place value (ones, twos, fours, …).

  • public static void main(String[] args), integer and long types, and printing with System.out.println.
  • Optional: String indexing with charAt, and parseInt(text, 2) from the Java standard library.

What does binary to decimal mean?

Each bit position i (starting at 0 on the right) contributes bi · 2i where bi ∈ {0, 1}. The decimal value is the sum of those contributions.

We just need a safe way to walk the bits and add their weighted contributions.

Binary base 2
Decimal base 10
Example 1010102 = 42

Expanded form

Reading 101010 from most to least significant bit (left to right as written),

1010102

1·25 + 0·24 + 1·23 + 0·22 + 1·21 + 0·20 = 32 + 8 + 2 = 42.

Intuition

10102 Decimal 10
Sum
8 + 2 = 10
1112 Decimal 7
Sum
4 + 2 + 1 = 7

Takeaway: each 1 flips on a power of two; each 0 skips that power.

Live preview

Enter a string of 0 and 1 characters (optional spaces). Uses parseInt(s, 2) in JavaScript for a quick decimal value. Empty or invalid characters are rejected.

For long strings, JavaScript may lose precision past 53 bits.

Live result
Press “Convert” to see the decimal value.

Algorithm (digit-stored form)

Goal: interpret a nonnegative integer whose decimal digits are only 0 or 1 as a binary pattern and return its decimal value.

Start value = 0, weight 1

Weight will double each step: 1, 2, 4, …

While the working number is nonzero

Take d = n % 10. If d is not 0 or 1, reject. Else add d * weight to value.

Shift

Divide n by 10, multiply weight by 2, repeat.

📜 Pseudocode

Pseudocode
function binaryDigitsToDecimal(n):  // n has only 0/1 decimal digits
    value ← 0
    weight ← 1
    while n > 0:
        d ← n mod 10
        if d not in {0, 1}: return error
        value ← value + d * weight
        n ← floor(n / 10)
        weight ← weight * 2
    return value
1

Digit peel (integer 101010, no Math.pow)

Matches the reference flow but uses an exact doubling weight instead of Math.pow(2, i), validates digits, and widens the accumulator.

java
public class Main {

    // Returns true if n contains only decimal digits 0 and 1 (and n >= 0)
    static boolean isBinaryDigitForm(long n) {
        if (n < 0) {
            return false;
        }
        if (n == 0) {
            return true; // single 0 bit
        }
        while (n > 0) {
            long d = n % 10;
            if (d > 1) {
                return false;
            }
            n /= 10;
        }
        return true;
    }

    // Converts e.g. 101010 (decimal digits) to 42; returns -1 on invalid input
    static long binaryDigitsToDecimal(long binaryForm) {
        if (!isBinaryDigitForm(binaryForm)) {
            return -1;
        }

        long value = 0;
        long weight = 1;
        long n = binaryForm;

        while (n > 0) {
            long digit = n % 10;
            value += digit * weight;
            n /= 10;
            weight *= 2;
        }

        return value;
    }

    public static void main(String[] args) {
        long binaryForm = 101010L;
        long dec = binaryDigitsToDecimal(binaryForm);

        if (dec < 0) {
            System.out.println("Invalid binary digit pattern.");
            return;
        }

        System.out.println("Binary (digit form): " + binaryForm);
        System.out.println("Decimal: " + dec);
    }
}

Explanation

The least significant decimal digit of 101010 is the least significant binary bit, so the first peeled digit pairs with weight 1, then 2, then 4, and so on.

weight *= 2;

Exact powers of two. Replaces Math.pow(2, i) without floating point.

if (d > 1) return false;

Reject invalid “binary” digits. A digit 29 must not be treated as a bit.

2

Horner’s method on a bit string

Natural when input arrives as text: scan most-significant bit first without reversing.

java
public class Main {

    // Returns -1 if s is null/empty or contains non-binary characters
    static long binaryStringToDecimal(String s) {
        if (s == null) {
            return -1;
        }

        String trimmed = s.trim();
        if (trimmed.isEmpty()) {
            return -1;
        }

        long value = 0;

        for (int i = 0; i < trimmed.length(); i++) {
            char c = trimmed.charAt(i);
            if (c != '0' && c != '1') {
                return -1;
            }
            int bit = c - '0'; // 0 or 1
            value = value * 2 + bit;
        }

        return value;
    }

    public static void main(String[] args) {
        String bits = "101010";
        long dec = binaryStringToDecimal(bits);

        if (dec < 0) {
            System.out.println("Invalid binary string.");
            return;
        }

        System.out.println("Binary (string): " + bits);
        System.out.println("Decimal: " + dec);
    }
}

Explanation

Each step doubles the running value (like a left shift in binary) and adds the new bit.

value = value * 2 + bit;

Horner update. Equivalent to a shift-and-add; in bit form you could also use (value << 1) | bit.

Optimization

Bit shifts. When you already have validated 0/1 ints, value |= (bit << i) or a shift-and-add approach can replace multiply-add patterns.

Library path. For whole-string conversion in day-to-day Java, Integer.parseInt(text, 2) or Long.parseLong(text, 2) is standard if the input length fits the chosen type.

Interview: explain both LSD peel and Horner; mention validation and overflow.

❓ FAQ

The classic classroom trick stores the bit pattern as a decimal integer whose digits are only 0 and 1. The code peels digits with % 10. In real Java source, you could use 0b101010 as a binary literal, or more commonly a string like "101010" and parse it.
Math.pow works in floating point, which can round incorrectly for larger exponents. Integer doubling (multiplying a running power of two by 2) or bit shifts for 0/1 digits keeps the sum exact for typical sizes.
That is not a valid binary digit. The samples validate each digit and either return a sentinel value or print an error message so garbage digits are not treated as bits.
Scan left to right: start value 0, then for each character c, value = value * 2 + (c - '0'). That avoids reversing digits and matches how we read the string naturally.
Yes. Many bits or a large accumulated decimal can exceed int or even long. Widen types or check bounds for your problem constraints.
Proportional to the number of bits or digits: O(k) for k binary digits.

🔄 Input / output examples

Example 1 prints the digit-form value and decimal. Example 2 prints the string and decimal.

Input formMeaningDecimal
101010L (long)Six-bit pattern stored as decimal digits42
"101010" stringSame pattern42
102LInvalid digit 2Error / -1 in sample

Edge cases and pitfalls

Confusing the digit-stored integer with a binary literal is the main conceptual trap; invalid digits and overflow are the main engineering traps.

Meaning

101010 in Java source

That token is a decimal integer unless you use the binary literal prefix 0b. The conversion routine here interprets its decimal digits as bits.

Digits

Values outside {0,1}

Without validation, a digit like 9 would be treated as 9 · 2k in the peel loop—nonsense for binary.

Floats

Math.pow(2, i)

Can mis-round for large i. Prefer integer doubling or exact shifts.

Length

Very long bit strings

Horner on long overflows when the true value exceeds the type; use BigInteger or a wider type policy for serious big-integer tasks.

⏱️ Time and space complexity

ApproachTimeExtra space
Digit peel or Horner on k bitsO(k)O(1)

Both sample programs use only a few scalar variables besides input storage.

Summary

  • Math: sum of bi 2i for bits bi.
  • Code: digit peel with doubling weight, or Horner on a String; avoid naive Math.pow for exact integers.
  • Watch-outs: meaning of 101010 in Java source, digit validation, overflow on long strings.
Did you know?

The pattern 101010 in base two means 32 + 8 + 2 = 42 in base ten. In the first Java sample, that pattern is stored as the ordinary decimal integer 101010 so each base-ten digit is a binary bit; it is not the Java binary literal 0b101010.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful