Decimal to Binary Example in Java

public class DecimalToBinaryExample {

	public static void decimalToBinaryFormat(int inputNum) {
		System.out.print("\nBinary of "+inputNum +" is: ");
		
		int binary[] = new int[20];
		int index = 0;
		
		while (inputNum > 0) {
			binary[index++] = inputNum % 2;
			inputNum = inputNum / 2;
		}
		for (int i = index - 1; i >= 0; i--) {
			System.out.print(binary[i]);
		}
		
	}

	public static void main(String a[]) {
		decimalToBinaryFormat(7);
		decimalToBinaryFormat(20);
		decimalToBinaryFormat(30);
	}
}
Output
Binary of 7 is: 111 Binary of 20 is: 10100 Binary of 30 is: 11110










Related Examples


Write a program to check if an input String is Palindrome or not?
Calculate the factorial of a given number using Java?
How to reverse a number in Java?
Write a program to convert from decimal to binary?
Producer Consumer Example in Thread
Write a program to reverse a String?








Receive Latest Java Examples in Your Email: