Java Program to Convert Binary String to Decimal Using Wrapper Class
Last Updated :
12 May, 2022
Given a binary string as input, we need to write a program to convert the given binary string into its equivalent decimal number.
Examples:
Input : 1111
Output : 15
Input : 1001101
Output : 77
Input : 1101
Output : 13
The idea is to extract each character of a given binary string using charAt() and convert those characters into their corresponding primitive integer type using Character.getNumericValue() and store those converted integers into the primitive integer type array in reverse order. It works with long binary numbers like 20 bits or 30 bits. As shown in the figure below:
Binary String converted to primitive int type array and stored in reverse order
Below is the implementation of the above code idea:
Java
import java.lang.Math;
import java.util.Scanner;
class BinaryToDecimal {
static int convertToDec(String bin)
{
int [] binArray = new int [ 1024 ];
int eqv_dec = 0 ;
for ( int i = bin.length() - 1 ; i >= 0 ; i--) {
binArray[i]
= Character.getNumericValue(bin.charAt(i));
}
for ( int i = 0 ; i < bin.length(); i++) {
if (binArray[i] == 1 ) {
eqv_dec += ( int )Math.pow( 2 , bin.length() - 1
- i);
}
else
continue ;
}
return eqv_dec;
}
public static void main(String[] args)
{
String bin = "1101" ;
System.out.println( "Given Binary: " + bin);
int eqv_dec = convertToDec(bin);
System.out.println( "Equivalent Decimal Number: "
+ eqv_dec);
}
}
|
Output:
Given Binary: 1101
Equivalent Decimal Number: 13
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...