I'm very new to C, so I don't know much about it. Pointers are something I still haven't learned... I need to show a single character in decimal and binary. In decimals its easy but I can't get it to binary in any way... I get the ASCII number and compare it's module with 2 but it shows a really awkward number... what is wrong with the code?(It's in portuguese This is my code:
#include <stdio.h>
#include <conio.c> //library my professor created to assist his students
#include <string.h>
#define MAXIMO 8
int main( void )
{
char caracter;
int aux, resto[MAXIMO], contador, decimal, numero;
printf( "Digite um UNICO caracter: " );
caracter = getch();
numero = caracter;
decimal = caracter;
aux = 0;
do
{
if (numero % 2 == 0)
{
resto[aux] = 0;
}
else
{
resto[aux] = 1;
}
numero = numero / 2;
aux++;
}
while (numero >= '0');
//system("cls");
printf( "\n\n%d\n\n", aux );
printf( "\nCaracter em Binario: " );
for (contador = aux; contador >= 0; contador--)
{
printf( "%d", resto[contador] );
}
printf( "\nValor decimal do caracter: %d", decimal );
getch();
return 0;
}
somethings I use like getch(); and return 0; in the end are just so my teacher don't kill me... I don't fully know why it's there but it has to be.
contador = auxneeds to becontador = aux-1;asauxis one past the last index that was set in the while loop above that.while(numero >= '0');is also wrong.'0'and0are different values. You want the latter.getch();is there so that if the console output is to a popup window it won't just disappear before you can read any output. Thereturn 0;is there because the function type isint(althoughmainis an exception, it is not mandatory in this case to return a value).