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.
Using Integer.toBinaryString() method
You can simply use inbuilt Integer.toBinaryString() method to convert a decimal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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<integer> stack= new Stack<integer>(); 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(); } } </integer></integer> |
Output:
Enter decimal number:
32
Binary representation is : 100000
32
Binary representation is : 100000
That’s all convert decimal to binary in java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.