-
-
Save parzibyte/8511ef6d5711db491481fdf3dda56b6b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Main { | |
public static void main(String[] args) { | |
int[] decimales = { 0, 2, 5, 50, 120, 1023, 51, 52, 60, 100, 53, 54, 55, 56, 57, 16, 17 }; | |
for (int decimal : decimales) { | |
System.out.println("Convirtiendo decimal a binario el número " + decimal); | |
System.out.println("Manual: " + convertirDecimalABinarioManual(decimal)); | |
System.out.println("Usando funciones: " + convertirDecimalABinario(decimal)); | |
} | |
} | |
public static String convertirDecimalABinario(long decimal) { | |
return Long.toBinaryString(decimal); | |
} | |
public static String convertirDecimalABinarioManual(long decimal) { | |
if (decimal <= 0) { | |
return "0"; | |
} | |
StringBuilder binario = new StringBuilder(); | |
while (decimal > 0) { | |
short residuo = (short) (decimal % 2); | |
decimal = decimal / 2; | |
// Insertar el dígito al inicio de la cadena | |
binario.insert(0, String.valueOf(residuo)); | |
} | |
return binario.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment