Numbers are magical in mathematics. Decimal numbers are whole numbers, where the binary numbers contain 0’s and 1’s.
How to implement?
There are two methods to implement this program in java.
- 1. Using user defined code
- 2. Using Built-in function.
Let us implement this program in both ways.
1.Using user defined code:
It has following steps.
- · First, read the input from the user.
- · Using a while loop, until the decimal_no is greater than zero, repeat the process.
- · using mod function, find the remainder using mod by 2.
- · Next, decimal_no is divided by 2.
- · Finally, print the binary_no.
Program:
import
java.util.Scanner;
public class DecimalToBinaryEg1 {
public static void
main(String[] args) {
Scanner s1 =
new Scanner(System.in);
// Read the
Decimal number as input
System.out.print("Enter the decimal number: ");
int decimal_no
= s1.nextInt();
String
binary_no = "";
// Let us
Convert the logic
while
(decimal_no > 0) {
binary_no
= (decimal_no % 2) + binary_no;
decimal_no
= decimal_no / 2;
}
// Display the
Binary number
System.out.println("Binary number of decimal number: " +
binary_no);
s1.close();
}
}
Output:
Compile and run the program to get the output.
C:\raji\blog>javac DecimalToBinaryEg1.java
C:\raji\blog>java DecimalToBinaryEg1
Enter the decimal number: 78
Binary number of decimal number: 1001110
This is the program to convert the decimal number into
binary number using user defined code.
2.Using Built-in function:
If you want to use the built-in
function to convert the decimal number into binary number, the below program uses
the function “toBinaryString()”.
The code is given below.
import java.util.Scanner;
public class DecimalToBinaryEg {
public static void
main(String[] args) {
Scanner s1 =
new Scanner(System.in);
// Get the
Decimal number as input
System.out.print("Enter the decimal number: ");
int decimal_no
= s1.nextInt();
// Conversion
of decimal to binary using built-in function
String
binary_no = Integer.toBinaryString(decimal_no);
// Print the
Binary representation
System.out.println("The converted Binary number is: " +
binary_no);
s1.close();
}
}
While running this program, you get the below output.
C:\raji\blog>javac DecimalToBinaryEg.java
C:\raji\blog>java DecimalToBinaryEg
Enter the decimal number: 67
The converted Binary number is: 1000011
These are the two ways to implement the conversion of decimal
number into binary number. Hope this code is useful to you.
No comments:
Post a Comment