Binary to Decimal Conversion in Java — Definition, Examples and Program
A binary number is a number in base 2, containing only 0s and 1s. Converting a binary number to decimal (base 10) is essential in computer programming and digital systems.
How to Convert Binary to Decimal?
- Take the binary number as input.
- Start from the rightmost digit (least significant bit).
- Multiply each bit by 2 raised to its position index (starting from 0).
- Sum all these values to get the decimal equivalent.
Example 1
Binary Number: 1101
- (1 × 2³) + (1 × 2²) + (0 × 2¹) + (1 × 2⁰)
- 8 + 4 + 0 + 1 = 13
Decimal: 13
Example 2
Binary Number: 10101
- (1 × 2⁴) + (0 × 2³) + (1 × 2²) + (0 × 2¹) + (1 × 2⁰)
- 16 + 0 + 4 + 0 + 1 = 21
Decimal: 21
Java Program for Binary to Decimal Conversion
import java.util.Scanner;
public class BinaryToDecimal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a binary number: ");
String binary = sc.next();
int decimal = 0;
int length = binary.length();
for (int i = 0; i < length; i++) {
char bit = binary.charAt(length - 1 - i); // Start from rightmost bit
if (bit == '1') {
decimal += Math.pow(2, i);
}
}
System.out.println("Decimal of " + binary + " is " + decimal);
}
}
Sample Output
Enter a binary number: 1101
Decimal of 1101 is 13
Enter a binary number: 10101
Decimal of 10101 is 21
Practice Challenges
- Write a program to convert multiple binary numbers entered by the user into decimal.
- Modify the program to validate input (only 0s and 1s allowed).
- Write a program to convert binary to octal and hexadecimal without using built-in functions.
Binary to decimal conversion is a key concept in computer science and helps understand the working of digital systems. This Java program allows beginners to convert binary numbers step by step easily.