Binary to Decimal conversion in Java
Numbers that have only 2 digits, 0 and 1, are called binary numbers. They are expressed only in the base 2 number system. We know that the binary system is the native digital language of modern computers. But we are more accustomed to decimal numbers. Of course, you can convert binary numbers to decimal and vice versa. On the diagram below you can see an example binary to decimal conversion. 10101 is a binary number used to explain mathematical calculations. We just need to follow the 3 simple steps. Always take the digit from the right side of a binary number, multiply it with the power of 2 and then simply add them. You’ll get the decimal number that is 21 in this case. There are two ways for converting binary to decimal in java.- Using Java method
- Using custom logic
Java Prebuilt Method
Java provides us with the Integer.parseInt() method to convert the string into an integer. parseInt() method belongs to the Integer class.Syntax
public static int parseInt(String binaryNumber, int radix)
Example
public class ConvertingBinaryToDecimal {
public static void main(String args[]){
String binaryNumber="10101";
int decimalNumber=Integer.parseInt(binaryNumber,2);
System.out.println(decimalNumber);
}
}
Output
21
Using Custom Logic
We can also write a program in Java that receives an integer and converts it to a decimal number. Let’s look at an example to understand it.Example
public class ConvertingBinaryToDecimal {
// function for converting binary to decimal number
public static int getDecimalNumber(int binaryNumber){
int decimalNumber = 0;
int power = 0;
while(binaryNumber > 0){
//taking the rightmost digit from binaryNumber
int temp = binaryNumber%10;
//now multiplying the digit and adding it to decimalNumber variable
decimalNumber += temp*Math.pow(2, power);
//removing the rightmost digit from binaryNumber variable
binaryNumber = binaryNumber/10;
//incrementing the power variable by 1 to be used as power for 2
power++;
}
return decimalNumber;
}
public static void main(String args[]){
System.out.println("Decimal value is: "+getDecimalNumber(111010));
System.out.println("Decimal value is: "+getDecimalNumber(001010));
}
}
Output
Decimal value is: 58
Decimal value is: 24
GO TO FULL VERSION