Home »
Java Programs »
Java Number System Conversion Programs
Java program to convert number from Decimal to Binary
This program will convert integer (Decimal) number to its equivalent Binary Number.
There are two programs:
1) Without using any predefine method and
2) Using Integer.toBinaryString() method.
Without using any predefine method
//java program to convert decimal to binary
import java.util.*;
public class ConvDec2Bin {
public static void main(String args[]) {
int num, counter = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter any integer number: ");
num = sc.nextInt();
//to store maximum 32 bits of a number
int binaryVal[] = new int[32];
while (num > 0) {
binaryVal[counter++] = num % 2;
num = num / 2;
}
/*print binary values stored in binaryVal*/
for (int i = counter - 1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}
}
}
Output
Complie : javac ConvDec2Bin.java
Run : java ConvDec2Bin
Output
Enter any integer number: 12345
11000000111001
Using Integer.toBinaryString() method
//java program to convert decimal to binary
import java.util.*;
public class ConvDec2Bin {
public static void main(String args[]) {
int num;
Scanner sc = new Scanner(System.in);
System.out.print("Enter any integer number: ");
num = sc.nextInt();
String str = Integer.toBinaryString(num);
System.out.println("Binary number is : " + str);
}
}
Output
Complie : javac ConvDec2Bin.java
Run : java ConvDec2Bin
Output
Enter any integer number: 12345
Binary number is : 11000000111001
Java Number System Conversion Programs »