Java Convert Binary to Decimal

To convert a binary number to a decimal number in Java, you can use the parseInt() method from the Integer class, specifying that the number is in base 2 (binary). Here’s an example:

String binaryString = "110101";
int decimal = Integer.parseInt(binaryString, 2);
System.out.println(decimal);

In this example, the binary string "110101" is converted to the decimal value 53. The parseInt() method takes two arguments: the first argument is the string to be parsed, and the second argument is the base of the number being parsed (in this case, 2 for binary).

Note that the input string must be a valid binary number, containing only 0 and 1 characters. If the string contains any other characters, a NumberFormatException will be thrown.

Java Binary to Decimal conversion: Integer.parseInt()

Yes, the Integer.parseInt() method can be used in Java to convert a binary string to a decimal integer.

Here’s an example:

String binaryString = "101010";
int decimalValue = Integer.parseInt(binaryString, 2);
System.out.println("Binary " + binaryString + " is equal to decimal " + decimalValue);

In this example, the binary string "101010" is converted to the decimal integer value 42. The second argument to Integer.parseInt() is the radix, which is set to 2 to indicate that the string represents a binary value.

Note that the binary string must only contain the characters 0 and 1. If any other character is present, an exception will be thrown.

Java Binary to Decimal conversion: Custom Logic

If you prefer not to use the Integer.parseInt() method and want to implement your own logic to convert a binary string to a decimal integer in Java, you can follow these steps:

  1. Initialize a variable to store the decimal value and set it to 0.
  2. Loop through each character of the binary string from right to left.
  3. For each character, check if it is equal to '1'. If it is, add 2^i to the decimal value, where i is the position of the character (counting from right to left).
  4. After looping through all the characters, the decimal value is now calculated.

Here’s an example implementation:

String binaryString = "101010";
int decimalValue = 0;
int position = 0;
for (int i = binaryString.length() - 1; i >= 0; i--) {
    if (binaryString.charAt(i) == '1') {
        decimalValue += Math.pow(2, position);
    }
    position++;
}
System.out.println("Binary " + binaryString + " is equal to decimal " + decimalValue);

In this example, the binary string "101010" is converted to the decimal integer value 42. The loop starts from the rightmost character of the string and loops through each character, incrementing the position variable for each iteration. If the character is equal to '1', the decimal value is updated by adding 2^position to it. Finally, the decimal value is printed.

Note that this implementation assumes that the input binary string is valid, containing only the characters '0' and '1'.