Java Exercises: Convert a binary number to decimal number
Java Basic: Exercise-22 with Solution
Write a Java program to convert a binary number to decimal number.
Binary number: A binary number is a number expressed in the base-2 numeral system or binary numeral system. This system uses only two symbols: typically 1 (one) and 0 (zero).
Decimal number: The decimal numeral system is the standard system for denoting integer and non-integer numbers. It is also called base-ten positional numeral system.
Pictorial Presentation: Binary to Decimal number
Sample Solution:
Java Code:
import java.util.Scanner;
public class Exercise22 {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
long binaryNumber, decimalNumber = 0, j = 1, remainder;
System.out.print("Input a binary number: ");
binaryNumber = sc.nextLong();
while (binaryNumber != 0)
{
remainder = binaryNumber % 10;
decimalNumber = decimalNumber + remainder * j;
j = j * 2;
binaryNumber = binaryNumber / 10;
}
System.out.println("Decimal Number: " + decimalNumber);
}
}
Sample Output:
Input a binary number: 100 Decimal Number: 4
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to convert a decimal number to octal number.
Next: Write a Java program to convert a binary number to hexadecimal number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework