Hay tres formas de convertir un número decimal en un número binario:
1) Utilizando método toBinaryString () de la clase Integer.
2) Realice la conversión escribiendo su lógica sin utilizar métodos predefinidos.
3) Usando Stack
Método 1: usar el método toBinaryString ()
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)); } }
Producción:
Binary representation of 124: 1111100 Binary representation of 45: 101101 Binary representation of 999: 1111100111
Método 2: sin usar el método predeterminado
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); } }
Producción:
Binary representation of 124: 1111100 Binary representation of 45: 101101 Binary representation of 999: 1111100111
Método 3: decimal a binario usando 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(); } }
Producción:
Enter decimal number: 999 Binary representation is:1111100111