Binary to Decimal in Java
Convert a binary string to its decimal value without an inbuilt converter.
- Time
O(n) for n digits - Space
O(n), because toCharArray makes a copy; O(1) if you use charAt - Hints3
- Read2 min
To convert binary to decimal in Java without an inbuilt function, start at 0, read the digits from left to right, and for each one do decimal = decimal * 2 + digit. With an inbuilt function, use Integer.parseInt(binary, 2). For example, 1011 becomes 11.
Problem statement
Write a binary to decimal in Java program. You get a binary number as a string. Print its decimal value.
For example, 1011 is 8 + 0 + 2 + 1 = 11.
A string of 0s and 1s.
The decimal value.
Examples
1011111*8 + 0*4 + 1*2 + 1*1 = 11.
11111111255Eight ones add up to 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1.
Constraints
- 1 to 63 binary digits
- The value is not negative
Think before you code
Reveal the questions to ask yourself first
- What is each binary digit worth, starting from the right?
- If you add one more digit at the end, what happens to the old value?
- What should the program do with a digit such as 2?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- Start with
decimal = 0. - Read the digits from left to right.
- If a character is not 0 or 1, reject the input.
- For each digit:
decimal = decimal * 2 + digit.
You do not need Math.pow, and there is no need to count places. The reverse task is
decimal to binary.
Dry run
Walk through the example step by step
Converting 1011:
digit | decimal * 2 + digit | decimal
------+---------------------+--------
1 | 0 * 2 + 1 | 1
0 | 1 * 2 + 0 | 2
1 | 2 * 2 + 1 | 5
1 | 5 * 2 + 1 | 11
Solution
Reveal the full Java solution
public class BinaryToDecimal {
// No inbuilt conversion. Up to 63 binary digits fit in a long.
public static long toDecimal(String binary) {
if (binary.isEmpty() || binary.length() > 63) {
throw new IllegalArgumentException("Need 1 to 63 digits");
}
long decimal = 0;
for (char c : binary.toCharArray()) {
if (c != '0' && c != '1') {
throw new IllegalArgumentException("Not binary: " + c);
}
decimal = decimal * 2 + (c - '0');
}
return decimal;
}
public static void main(String[] args) {
System.out.println(toDecimal("1011")); // 11
System.out.println(toDecimal("11111111")); // 255
System.out.println(toDecimal("0")); // 0
}
}This is binary to decimal in Java without inbuilt function. Each step moves the old
value one place to the left (times 2) and adds the new digit. The input is limited to 63
digits so the answer always fits in a long.
Binary to decimal in Java inbuilt function
The second argument, 2, is the base. These calls are the binary to decimal in Java code
you would use in a real project:
System.out.println(Integer.parseInt("1011", 2)); // 11
System.out.println(Long.parseLong("11111111", 2)); // 255
System.out.println(new BigInteger("1".repeat(70), 2));
// 1180591620717411303423
Integer.parseInt throws NumberFormatException for bad input or a value too big for an
int. Read more in
exception handling in Java.
Binary to decimal in Java using recursion
Convert everything except the last digit, double it, and add the last digit.
static long recursive(String b) {
if (b.isEmpty()) return 0;
int last = b.length() - 1;
return recursive(b.substring(0, last)) * 2 + (b.charAt(last) - '0');
}
recursive("1011") returns 11. It makes a new string at each step, so the loop is
the better choice. This short version does not check for bad digits.
When the binary number is stored in an int
Some questions pass 1011 as an int. Take the last digit with % 10:
static int fromInt(int binary) {
int decimal = 0;
int place = 1; // 1, 2, 4, 8 ...
while (binary > 0) {
decimal += (binary % 10) * place;
place *= 2;
binary /= 10;
}
return decimal;
}
An int holds at most 10 decimal digits, so this only works for short binary numbers. Do
not write 01011 in code: a number starting with 0 is read as octal in Java.
More practice: check a power of two, Java operators and the Java full stack course.
O(n) for n digitsO(n), because toCharArray makes a copy; O(1) if you use charAtReview before the interview
Common mistakes
- Adding the char itself instead of c - '0'. The char '1' has the value 49.
- Using Math.pow, which works with double and can lose exactness on big numbers.
- Not checking for digits other than 0 and 1.
Edge cases to test
- 0 and 0000 both give 0.
- Leading zeros, such as 0011, are fine in a string.
- More than 63 digits needs BigInteger.
Interview follow-ups
- How would you handle negative numbers in two's complement?
- How would you convert a binary fraction such as 10.11?
- How would you change the code for base 8 or base 16?
Keep practising
Convert a Decimal Number to Binary
Hints · Dry run · SolutionSolve Similar problemCheck Whether a Number Is a Power of Two
Hints · Dry run · SolutionSolve Similar problemCheck Whether a String Contains Only Digits
Hints · Dry run · SolutionSolve Related learningOperators
TutorialLearn Related learningLoops
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
