Java program to convert binary number to decimal and vice versa

www.i‮tfig‬idea.com

Here's a Java program to convert a binary number to decimal and vice-versa:

import java.util.Scanner;

public class BinaryDecimalConverter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a binary number:");
        String binaryString = scanner.nextLine();

        int decimalNumber = binaryToDecimal(binaryString);
        System.out.println("The decimal equivalent of " + binaryString + " is " + decimalNumber);

        System.out.println("Enter a decimal number:");
        int decimalValue = scanner.nextInt();

        String binaryValue = decimalToBinary(decimalValue);
        System.out.println("The binary equivalent of " + decimalValue + " is " + binaryValue);
    }

    public static int binaryToDecimal(String binaryString) {
        int decimalNumber = 0;
        int base = 1;
        for (int i = binaryString.length() - 1; i >= 0; i--) {
            if (binaryString.charAt(i) == '1') {
                decimalNumber += base;
            }
            base *= 2;
        }
        return decimalNumber;
    }

    public static String decimalToBinary(int decimalValue) {
        String binaryValue = "";
        while (decimalValue > 0) {
            binaryValue = (decimalValue % 2) + binaryValue;
            decimalValue /= 2;
        }
        return binaryValue;
    }
}

In this program, we first prompt the user to enter a binary number using the Scanner class. We then call a method called binaryToDecimal to convert the binary number to a decimal value, and print the result to the console. We then prompt the user to enter a decimal number, and call a method called decimalToBinary to convert the decimal value to a binary value, and print the result to the console.

The binaryToDecimal method takes a binary string as input, and uses a for loop to iterate through the string from right to left. For each digit in the string, we check if it is a '1', and if so, add the corresponding power of 2 to the decimal number. We keep track of the current power of 2 using a variable called base, which is initialized to 1 and doubled at each iteration.

The decimalToBinary method takes an integer as input, and repeatedly divides the value by 2, keeping track of the remainders to build up the binary string. We add each remainder to the beginning of the string using string concatenation.

You can modify the binary and decimal values entered by the user to test the program with different values. Note that the program does not handle invalid input, such as non-binary values or negative numbers. You can add input validation code as needed.