Binary and decimal are two common numeral systems used in computing. Binary (base 2) is used by computers, while decimal (base 10) is what we typically use in everyday life. Converting between these two systems is a common operation in programming. In Java, you can easily convert binary to decimal using built-in functions or through manual methods.
Method 1: Using Integer.parseInt()
Java provides a convenient built-in method called Integer.parseInt() that can directly convert a binary string to its decimal representation. This method takes two arguments:
1. The string to convert.
2. The base of the numeral system (in this case, base 2 for binary).
Syntax:
int decimalValue = Integer.parseInt(binaryString, 2);
Example 1: Converting a Binary String to Decimal
public class BinaryToDecimal {
public static void main(String[] args) {
// Binary number as a string
String binaryString = "110101"; // example binary number
// Convert binary to decimal
int decimalValue = Integer.parseInt(binaryString, 2);
// Output the result
System.out.println("Binary: " + binaryString);
System.out.println("Decimal: " + decimalValue);
}
}
Explanation:
- “110101” is the binary number.
- Integer.parseInt(binaryString, 2) converts the binary string “110101” to its decimal equivalent.
Output:
Binary: 110101
Decimal: 52
Method 2: Manual Conversion
If you want to manually convert a binary number to decimal, you can process each bit of the binary number starting from the rightmost (least significant bit) and apply the powers of 2.
Example 2: Manual Conversion of Binary to Decimal
Let’s manually convert the binary string “101011” to decimal.
public class BinaryToDecimal {
public static void main(String[] args) {
String binaryString = "101011"; // example binary number
// Initialize variables for conversion
int decimalValue = 0;
int power = 0;
// Loop through each bit (from right to left)
for (int i = binaryString.length() - 1; i >= 0; i--) {
char bit = binaryString.charAt(i); // Get the bit at position i
if (bit == '1') {
decimalValue += Math.pow(2, power); // Add 2^position if bit is 1
}
power++;
}
// Output the result
System.out.println("Binary: " + binaryString);
System.out.println("Decimal: " + decimalValue);
}
}
Output:
Binary: 101011
Decimal: 43