Base Conversion
Writes a number in binary and hexadecimal.
- Level
- Advanced
- Topic:
- Math
- Concepts:
- Input & output
- Mientras
- Text
- Math
Open in Codoritmo
Run, change and debug this example in your browser.
What you'll learn
With repeated division, MOD gives each digit and Trunc the quotient. ConvertirATexto and Subcadena turn each remainder into its character.
Code
Algoritmo ConversionBases Definir numero, cociente, resto Como Entero Definir binario, hexadecimal, digitos Como Caracter digitos <- "0123456789ABCDEF" Escribir "Número entero positivo:" Leer numero // Divisiones sucesivas: los restos, leídos al revés, forman el número binario <- "" cociente <- numero Mientras cociente > 0 Hacer binario <- ConvertirATexto(cociente MOD 2) + binario cociente <- Trunc(cociente / 2) FinMientras hexadecimal <- "" cociente <- numero Mientras cociente > 0 Hacer resto <- cociente MOD 16 hexadecimal <- Subcadena(digitos, resto + 1, resto + 1) + hexadecimal cociente <- Trunc(cociente / 16) FinMientras Si numero = 0 Entonces binario <- "0" hexadecimal <- "0" FinSi Escribir numero, " en binario: ", binario Escribir numero, " en hexadecimal: ", hexadecimalFinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
Número entero positivo:User answer: 20242024 en binario: 111111010002024 en hexadecimal: 7E8
Challenge
Add a conversion to base 8 (octal).
Show hint
Copy the binary block and change the 2 into an 8.
Related examples
Prime Numbers
Finds every prime number up to a limit.
IntermediateGCD and LCM
Computes the greatest common divisor and the least common multiple.
IntermediateCaesar Cipher
Encrypts a message by shifting each letter of the alphabet.
Advanced