Java program to convert decimal to binary

Java program to convert decimal to binary


There are three following ways to convert Decimal number to binary number:
1) Using toBinaryString() method of Integer class.
2) Do conversion by writing your own logic without using any predefined methods.
3) Using Stack

Method 1: Using toBinaryString() method

class DecimalBinaryExample{

public static void main(String a[]){
System.out.println("Binary representation of 124: ");
System.out.println(Integer.toBinaryString(124));
System.out.println("\nBinary representation of 45: ");
System.out.println(Integer.toBinaryString(45));
System.out.println("\nBinary representation of 999: ");
System.out.println(Integer.toBinaryString(999));
}
}
Output:
Binary representation of 124: 
1111100

Binary representation of 45:
101101

Binary representation of 999:
1111100111

Method 2: Without using predefined method

class DecimalBinaryExample{

public void convertBinary(int num){
int binary[] = new int[40];
int index = 0;
while(num > 0){
binary
[index++] = num%2;
num
= num/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
}

public static void main(String a[]){
DecimalBinaryExample obj = new DecimalBinaryExample();
System.out.println("Binary representation of 124: ");
obj
.convertBinary(124);
System.out.println("\nBinary representation of 45: ");
obj
.convertBinary(45);
System.out.println("\nBinary representation of 999: ");
obj
.convertBinary(999);
}
}
Output:
Binary representation of 124: 
1111100
Binary representation of 45:
101101
Binary representation of 999:
1111100111

Method 3: Decimal to Binary using Stack

import java.util.*;
class DecimalBinaryStack
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);

// Create Stack object
Stack<Integer> stack = new Stack<Integer>();

// User input
System.out.println("Enter decimal number: ");
int num = in.nextInt();

while (num != 0)
{
int d = num % 2;
stack
.push(d);
num
/= 2;
}

System.out.print("\nBinary representation is:");
while (!(stack.isEmpty() ))
{
System.out.print(stack.pop());
}
System.out.println();
}
}
Output:
Enter decimal number: 
999

Binary representation is:1111100111

Post a Comment

Previous Post Next Post