Linux Tutorial
In this java program, we are going to learn how to automate converting decimal numbers to binary numbers.
Steps to convert decimal to binary numbers
1) Divide the given decimal number by 2 where it gives the result along with the remainder. 2) If the given decimal number is even, then the result will be whole and it gives the remainder “0” 3) If the given decimal number is odd, then the result is not divided properly and it gives the remainder “1”. 4) By placing all the remainders in order where the Least Significant Bit (LSB) at the top and Most Significant Bit (MSB) at the bottom.
Example,
Decimal number is 23.
Solution
2 | 23
________
2 | 11……………1
________
2 | 5…………….1
________
2 | 2…………….1
________
1…………….0
So, the binary equivalent is,
(23)10 = (10111)2
In decimal to binary conversion, we convert a base 10 number to base 2 number.
import java.io.*; import java.util.*; public class DecimalToBinary { public static void main(String[] args) { int number; long binaryNumber = 0; int remainder, i = 1; Scanner in = new Scanner(System.in); System.out.print("Enter decimal number: "); number = in.nextInt(); while (number!=0) { remainder = number % 2; number /= 2; binaryNumber += remainder * i; i *= 10; } System.out.println("Binary number: "+ binaryNumber); } }
Output:
Enter decimal number: 23 Binary number: 10111
import java.io.*; import java.util.*; public class DecimalToBinary { public static void main(String[] args) { int number; long binaryNumber = 0; int remainder, i = 1; Scanner in = new Scanner(System.in); System.out.print("Enter decimal number: "); number = in.nextInt(); for (;number!=0;i*=10) { remainder = number % 2; number /= 2; binaryNumber += remainder * i; } System.out.println("Binary number: "+ binaryNumber); } }
Output:
Enter decimal number: 23 Binary number: 10111
We can also make the java program with only for loop statement with no block statements,
import java.io.*; import java.util.*; public class DecimalToBinary { public static void main(String[] args) { int number; long binaryNumber = 0; int remainder, i = 1; Scanner in = new Scanner(System.in); System.out.print("Enter decimal number: "); number = in.nextInt(); for (;number!=0;remainder = number % 2, number /= 2,binaryNumber += remainder * i, i*=10); System.out.println("Binary number: "+ binaryNumber); } }
Output:
Enter decimal number: 23 Binary number: 10111
Linux Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page