In this post, we will see how to convert decimal to binary in java.
There are lot of ways to convert decimal to binary in java.Let’s explore them one by one.
[toc]
Using Integer.toBinaryString() method
You can simply use inbuilt Integer.toBinaryString() method to convert a decimal
package org.arpit.java2blog;
public class DecimalToBinaryInBuiltMain {
public static void main(String[] args) {
System.out.println("Binary representation of 12 : "+ Integer.toBinaryString(12));
System.out.println("Binary representation of 32 : "+Integer.toBinaryString(32));
System.out.println("Binary representation of 95 : "+Integer.toBinaryString(95));
}
}
Output:
Binary representation of 12 : 1100
Binary representation of 32 : 100000
Binary representation of 95 : 1011111
Binary representation of 32 : 100000
Binary representation of 95 : 1011111
Using iterative array approach
package org.arpit.java2blog;
import java.util.Scanner;
public class DecimalToBinaryArrayMain
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a decimal number");
int n=sc.nextInt();
int binary[]=new int[100];
int index = 0;
while(n > 0)
{
binary[index++] = n%2;
n = n/2;
}
System.out.print("Binary representation is : ");
for(int k = index-1;k >= 0;k--)
{
System.out.print(binary[k]);
}
sc.close();
}
}
Output:
Enter a decimal number
12
Binary representation is : 1100
12
Binary representation is : 1100
Using stack
package org.arpit.java2blog;
import java.util.Scanner;
import java.util.Stack;
public class DecimalToBinaryStackMain
{
public static void main(String[] arg)
{
Scanner scanner= new Scanner(System.in);
Stack stack= new Stack();
System.out.println("Enter decimal number: ");
int num = scanner.nextInt();
while(num != 0)
{
int d = num % 2;
stack.push(d);
num /= 2;
}
System.out.print("Binary representation is : ");
// Print binary presentation
while (!(stack.isEmpty() ))
{
System.out.print(stack.pop());
}
scanner.close();
}
}
Output:
Enter decimal number:
32
Binary representation is : 100000
32
Binary representation is : 100000
That’s all convert decimal to binary in java.