Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaJava Program to Convert Binary String to Decimal Using Wrapper Class

Java Program to Convert Binary String to Decimal Using Wrapper Class

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

Binary String converted to primitive int type array and stored in reverse order

Below is the implementation of the above code idea:

Java




//  Program to Convert a given Binary String to
// its equivalent decimal number
  
import java.lang.Math;
import java.util.Scanner;
  
class BinaryToDecimal {
    // convertToDec() Method
    // performs the conversion of
    // Binary to Decimal
    static int convertToDec(String bin)
    {
        int[] binArray = new int[1024];
        int eqv_dec = 0;
  
        // Converting characters of Binary String to
        // primitive integer and storing it in the Array in
        // reverse order!!
        for (int i = bin.length() - 1; i >= 0; i--) {
            binArray[i]
                = Character.getNumericValue(bin.charAt(i));
        }
  
        // Evaluating Equivalent Decimal Number from the
        // Binary Array!!
        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;
    }
  
    // Driver Code!
    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

RELATED ARTICLES

Most Popular

Recent Comments