Created
April 20, 2024 00:36
-
-
Save ppazos/a5aedc6442c040120eb2d25dcbb9bdac to your computer and use it in GitHub Desktop.
Transforma un número decimal a uno binario en Groovy
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
int n = 1024 // entrada | |
String binario = '' // numero binario como string para poder verlo | |
int c = n | |
while (c > 1) | |
{ | |
// modulo (%) da 0 cuando el numero es par y da 1 cuando el numero impar | |
// los numeros pares en binario terminan en cero, y los impoares en 1, | |
// entonces esto sirve para tomar el ultimo bit y saber si es 0 o 1. | |
binario = (c % 2).toString() + binario | |
// el shift mueve todo el numero un bit a la derecha, para que en el | |
// siguiente bucle, se procese el ultimo bit | |
c = c >> 1 | |
} | |
// se agrega el ultimo bit restante del numero | |
binario = c.toString() + binario | |
println binario |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment