Exercise:
Write a Java Program to convert binary number to decimal.
Click Here to View the Solution!
public class BinaryToDecimal {
public static void main(String[] args) {
long number = 101101101;
int decimal = convertBinaryToDecimal(number);
System.out.printf("%d in binary = %d in decimal", number, decimal);
}
public static int convertBinaryToDecimal(long number)
{
int decimalNumber = 0, i = 0;
long remainder;
while (number != 0)
{
remainder = number % 10;
number /= 10;
decimalNumber += remainder * Math.pow(2, i);
++i;
}
return decimalNumber;
}
}
Click Here to View the Output!
101101101 in binary = 365 in decimal
Click Here to View the Explanation!
- This program deals with transforming a binary number into a decimal number with the help of
convertBinaryToDecimal()
function. - Primarily, In the
main()
function a number ‘101101101
; with data type defined as ‘long
’, is declared. - This number is passed as an argument to
convertBinaryToDecimal()
function. - Two variables: ‘
decimalNumber
’ and ‘remainder
’, declared in the function, keep track of values during each execution. Here ‘i’ keeps track of power of ‘2’, being increased by 1 with each pass as long as the number does not approach ‘0’. - During the first step of execution, the remainder (to 10) for the given value is calculated. Then the number is divided by ‘10’, to be passed for the next iteration.
- In the third statement of the function, the product of remainder and power (i.e. ‘0’ initially) of ‘2’, is calculated and stored in the variable ‘
decimalNumber
’. - The value of ‘i’ gets increased by ‘1’ in the fourth statement of the function.
- This process continues till the value of number variable becomes ‘0’. After that the function returns a number ‘
365
’ which is the decimal value for the given number ‘101101101
.