Conversor de bases numéricas [ESP-ENG] | C++

avatar

Saludos ciudadanos, por acá vengo de vuelta con más programación, esta vez con un conversor de bases numéricas como lo habrán visto en el título. Elegí hacer este conversor porque hace tiempo estuve ayudando a mis primos pequeños a realizar su tarea sobre conversión de sistema decimal a binario y eso me trajo recuerdos de mi tiempo en la escuela... Y de como no le encontraba mucho sentido a estudiar eso si no había una aplicación útil a corto o mediano plazo. A menos que estudiases algo relacionado a informática y entonces lo vieras en las aplicaciones de lenguaje binario y algunas cosas más.

Además de esta razón, otro detonador fue el leer algunos post de retos matemáticos que incluían responder la pregunta de cómo se escribiría un número en otra base numérica. Como por ejemplo.

Greetings citizens, here I come back with more programming, this time with a number base converter as you may have seen in the title. I chose to make this converter because some time ago I was helping my little cousins to do their homework about decimal to binary conversion and that brought back memories of my time at school... And how I didn't see much point in studying it if there was no useful application in the short or medium term. Unless you studied something related to computer science and then you saw it in the binary language applications and some other things.

In addition to this reason, another trigger was reading some mathematical challenge posts that included answering the question of how a number would be written in another number base. Such as for example..


Portada con efectasos.jpg

Png (Old Monitor), Png (BinaryCube), Png (Black and White Hand). Edited with Photoshop CS6

Programación c++.png

Para empezar usé las librerías de siempre pero incluí "math.h" para usar la función "pow" que sería para elevar, es decir, potenciación numérica. Las primeras dos funciones son recicladas del programa de calculador de divisores, estas las usé para verificar la entrada por teclado. Modifiqué el texto que informa al usuario para adecuarlo al conversor y añadí un condicional que limita el tamaño del número ingresado, esto porque el máximo aproximado que encontré por tanteo para que en la conversión más grande que me aparecía, fue "480.000", si aumentaba este número se manifestaban errores de sobrecarga de la variable "long long int".

Luego aparece la función "conv_sistema", esta empezó siendo solo para base 5, pero luego la estandaricé para reducir la cantidad de código presente y aumentar las opciones para el resultado final. El algoritmo se basa en dos auxiliares, un contador y un do-while, el segundo auxiliar toma el módulo de la división a partir de la opción referente a la conversión elegida, es decir, si el usuario eligió "convertir a sistema ternario", entonces se tomará el módulo (restante de la división) del número entre 3, luego se multiplicará por 10 elevado al valor del contador, si es cero pues 10 elevado a la 0 es igual a 1 por propiedad y esto dará igual al mismo módulo calculado. Finalmente se le suma el propio valor de aux2 calculado en la vuelta anterior.

Esto porque para lograr la nueva cantidad es necesario agrupar los módulos y colocarlos correctamente según su posición numérica. Por ejemplo, 3200 es igual a 6200 en sistema octal. Ese 6200 nace de la agrupación de los módulos (0 * 1 + 0 * 10 + 2 * 100 + 6 * 1000). Estos módulos se generan a partir de la división entre 8, de la cantidad ingresada, pero reducida en cada iteración a través de la variable "aux", es decir el primer auxiliar. Luego es actualizada a partir del mismo, n=aux.

Para entender mejor el proceso de conversión, acá debajo dejo una captura a un blog de una profesora de primaria llamada "Martha Valero" que dejó un buen ejemplo de cómo se realiza. Además también de un link que lleva a una explicación paso a paso de una página llamada "Edukativos, apuntes para universitarios".

Recapitulando, nsystem está asociado a la base numérica elegida por el usuario, es decir a la que desea convertir el número ingresado, los auxiliares ayudan a las iteraciones y el proceso de cálculo de la nueva cantidad, el contador (cont) se vincula a la potenciación, respecto a agrupar los módulos para crear la nueva cantidad y "n" es el número ingresado que debe pasar antes por la función que comprueba que es válido para ser convertido. La función "exit" es simplemente un retorno para dar un poco de orden a las transiciones en el menú y las pantallas con los resultados.

To start I used the usual libraries but I included "math.h" to use the "pow" function which would be for raising, i.e. numerical powering. The first two functions are recycled from the divisor calculator program, these I used to verify the keyboard input. I modified the text that informs the user to adapt it to the converter and I added a conditional that limits the size of the number entered, this because the approximate maximum that I found by trial and error so that in the largest conversion that appeared to me, was "480,000", if I increased this number, errors of overload of the variable "long long int" were manifested.

Then appears the function "conv_sistema", this started being only for base 5, but then I standardized it to reduce the amount of code present and increase the options for the final result. The algorithm is based on two auxiliaries, a counter and a do-while, the second auxiliary takes the modulus of the division from the option concerning the chosen conversion, that is, if the user chose "convert to ternary system", then it will take the modulus (remaining of the division) of the number by 3, then it will be multiplied by 10 raised to the value of the counter, if it is zero then 10 raised to the 0 is equal to 1 by property and this will give equal to the same calculated modulus. Finally the own value of aux2 calculated in the previous round is added.

This is because to achieve the new quantity it is necessary to group the modules and place them correctly according to their numerical position. For example, 3200 is equal to 6200 in octal system. That 6200 is born from the grouping of the modules (0 * 1 + 0 * 10 + 2 * 100 + 6 * 1000). These modules are generated from the division by 8, of the quantity entered, but reduced in each iteration through the variable "aux", that is to say the first auxiliary. It is then updated from it, n=aux.

To better understand the conversion process, here below I leave a screenshot to a blog of a primary school teacher called "Martha Valero" who left a good example of how it is done. Also a link to a step-by-step explanation of a page called "Edukativos, apuntes para universitarios".

Recapitulating, nsystem is associated to the numerical base chosen by the user, that is to say to the one you want to convert the number entered, the auxiliaries help the iterations and the process of calculating the new quantity, the counter (cont) is linked to the potentiation, regarding to group the modules to create the new quantity and "n" is the number entered that must pass before through the function that checks that it is valid to be converted. The "exit" function is simply a return to give some order to the transitions in the menu and the screens with the results.

Programación c++.png

image.png
Explicación de cómo realizar un cambio de base numérica, Martha Valero

image.png
Explicación paso a paso para la realización de un cambio de base numérica, Edukativos.com

Programación c++.png

image.png

image.png

image.png

Programación c++.png

La función "selector" ya es bastante frecuente en mis post de C++ y es porque la reciclo bastante por ser una buena forma de comunicar las opciones al usuario. Esta vez decidí hacerla más coqueta al añadir un marco al texto. Sumado a esto cubrí las 10 posibles opciones de 1 caracter. En la opción 1 se muestra una lista con la cifra convertida a 8 sistemas distintos, desde el binario hasta el nonario.

Las opciones siguientes cubren el sistema binario, ternario, cuaternario, quinario, senario, septenario, octal y nonario por separado. Y el 0 se usa para salir del programa. Para cubrir cada opción llamo a la función "comprobador" para filtrar la cantidad ingresada por teclado y luego "conv_sistema" para realizar las operaciones necesarias para la conversión.

The "selector" function is already quite frequent in my C++ posts and it is because I recycle it quite a lot as it is a good way to communicate the options to the user. This time I decided to make it more flirtatious by adding a frame to the text. In addition to this I covered the 10 possible 1 character options. Option 1 shows a list with the number converted to 8 different systems, from binary to nonary.

The following options cover binary, ternary, quaternary, quinary, senary, septenary, octal and nonary separately. And 0 is used to exit the program. To cover each option I call the function "tester" to filter the quantity entered by keyboard and then "conv_system" to perform the necessary operations for the conversion.

image.png

image.png

image.png

image.png

image.png

Programación c++.png

image.png

image.png

image.png

Programación c++.png

Y bueno eso es todo por hoy, espero que este conversor te resulte útil para tu camino de aprendizaje, si tienes algún consejo para mejorar será bien recibido, bendiciones!

And well that's all for today, I hope you find this converter useful for your learning path, if you have any advice to improve it will be well received, blessings!

Programación c++.png


Redes actualizada.gif


Puedes seguirme por acá si lo deseas:
You can follow me here if you want:

Cuenta secundaria
(Dibujos, edición y juegos) | Secondary account (Drawings, editing and games)



0
0
0.000
5 comments
avatar

Interesante. Motivas a regresar a programación

0
0
0.000
avatar

Aún estoy en la relación amor-odio, pero sí, tenerla presente está genial. Gracias por pasarse por acá, don Miguel.

0
0
0.000
avatar

Congratulations @gabrielr29! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

You received more than 15000 upvotes.
Your next target is to reach 20000 upvotes.
You made more than 900 comments.
Your next target is to reach 1000 comments.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Check out the last post from @hivebuzz:

Hive Power Up Month - Feedback from February day 25
Introducing NFT for Peace
Support the HiveBuzz project. Vote for our proposal!
0
0
0.000
avatar

Muchos programadores que no son hablan el Ingles muy bien sienten que no podrian conseguir trabajo pero estan equivocados. Ahora mismo en la industria blockchain esta muy requerido y bien remunerado cualquier conocimiento profesional, especialmente si se relaciona a computadores.

Me tomo un momento para invitarte a ti y a quizas tus lectores con habilidades de programacion, a que se suscriban a esta comunidad nueva en donde se publican trabajos en el sector blockchain. Saludos!


blockchainjobs.gif

0
0
0.000