Certainly! Here's an example Java code that converts a binary number to its decimal equivalent:
public class BinaryToDecimalConverter {
public static void main(String[] args) {
String binaryNumber = "101010"; // Example binary number
int decimalNumber = binaryToDecimal(binaryNumber);
System.out.println("Binary Number: " + binaryNumber);
System.out.println("Decimal Number: " + decimalNumber);
}
public static int binaryToDecimal(String binaryNumber) {
int decimalNumber = 0;
int power = 0;
// Start from the rightmost bit and move towards the left
for (int i = binaryNumber.length() - 1; i >= 0; i--) {
int bit = binaryNumber.charAt(i) - '0'; // Convert char to integer
// Multiply the bit value with 2 raised to the power
decimalNumber += bit * Math.pow(2, power);
power++;
}
return decimalNumber;
}
}
In this example, we have a method called binaryToDecimal that takes a binary number as a string parameter and returns its decimal equivalent as an integer. The main method demonstrates how to use this method by converting the binary number "101010" to decimal.
The binaryToDecimal method works by iterating through each bit of the binary number from right to left. It converts the character at each position to an integer by subtracting the ASCII value of '0'. It then multiplies the bit value with 2 raised to the appropriate power and adds it to the decimalNumber variable. The power starts from 0 and increments by 1 for each subsequent bit.
After the loop, the decimalNumber is returned and printed in the main method.
When you run the code, it will output:
Binary Number: 101010
Decimal Number: 42
So, the binary number "101010" is equivalent to the decimal number 42.