Java program to convert Decimal Number to Binary Number
I was reading the first chapter of my class eleventh textbook. While reading the chapter, I came across a topic "Conversion of Decimal Number System to Binary Number System". In that chapter, I found the method of converting the decimal number to the binary number.
Decimal number system means the number system which is base 10 or uses 10 digits. Like the one we use in maths with digits from 0 to 9.
Binary Number system means the number system that uses the base 2 or only 2 digits. The number system of 0s and 1s are called Binary Number System, which is also the language of computers. In programming, 0 means off or false and 1 means true or on.
The method for converting the decimal number to binary number is:
First the number is divided by 2 and the remainder whether it is 0 or 1 is noted. The first remainder is called Least Significant Bit (LSB). Then the quotient of the number is again divided by 2 and the remainder is noted. This process is repeated till the quotient becomes zero. The last remainder noted before the quotient became zero is called Maximum Significant Bit (MSB).
I made this program with a single while loop which runs till the number which is input by the user becomes zero. Inside the loop, the remainder is found out with modulus, and it is noted as a string.
At last, all the remainder is added to another variable from left to right, as the first remainder (LSB) will come last and last remainder (MSB) will come first.
// Converter from decimal number to binary number
// Method: Divide number by 2 and note the remainder. First remainder will be LSB. Now, take the quotient and divide again by 2. Repeat the process till quotient becomes 0. The last remainder will be MSB. Arrange from MSB to LSB.
import java.util.*;
class Converter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n;int p; String a; String s="";
System.out.println("Enter decimal number");
n = in.nextInt();
while(n>0){
p = n%2;
a = String.valueOf(p);
s = p+s;
n=n/2;
}
System.out.println("Binary number:" + s);
}
}
Comments
Post a Comment