how to convert a decimal number to binary in java code example
Example 1: Java program to convert decimal number to binary & count number of 1s
// decimal to binary conversion in java
import java.util.Scanner;
public class DecimalBinaryDemo
{
public static void main(String[] args)
{
int number, count = 0, temp;
String strConvert = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a decimal number : ");
number = sc.nextInt();
// decimal to binary java
while(number > 0)
{
temp = number % 2;
if(temp == 1)
{
count++;
}
strConvert = strConvert + " " + temp;
number = number / 2;
}
System.out.println("Decimal to binary in java : " + strConvert);
System.out.println("Number of 1s : " + count);
sc.close();
}
}
Example 2: Java program to convert decimal to binary using toBinaryString and stack
Convert decimal to binary using stack in java
import java.util.*;
public class DecimalBinaryExample
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Stack<Integer> numStack = new Stack<Integer>();
System.out.println("Please enter a decimal number : ");
int number = sc.nextInt();
while(number != 0)
{
int a = number % 2;
numStack.push(a);
number /= 2;
}
System.out.println("Binary number : ");
while(!(numStack.isEmpty()))
{
System.out.print(numStack.pop());
}
System.out.println();
sc.close();
}
}
Example 3: convert decimal to binary in java
public class DecimalToBinaryExample2{
public static void toBinary(int decimal){
int binary[] = new int[40];
int index = 0;
while(decimal > 0){
binary[index++] = decimal%2;
decimal = decimal/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
System.out.println();//new line
}
public static void main(String args[]){
System.out.println("Decimal of 10 is: ");
toBinary(10);
System.out.println("Decimal of 21 is: ");
toBinary(21);
System.out.println("Decimal of 31 is: ");
toBinary(31);
}}