Vinícius Breda Vinícius Breda - 1 month ago 11
C Question

Need help converting from ASCII to binary

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.

Answer

Your code had some errors in the while condition:

#include <stdio.h>
#include <string.h>
#define MAXIMO 8

int main( void )
{
  char caracter;
  int aux, resto[MAXIMO], contador, decimal, numero;
  printf( "Digite um UNICO caracter: " );
  caracter = getchar(); // I used getchar instead of 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); // > than 0 not >= '0' 
  //system("cls");
  printf( "\n\n%d\n\n", aux );
  printf( "\nCaracter em Binario: " );
  for (contador = aux-1; contador >= 0; contador--) //aux-1
  {
    printf( "%d", resto[contador] );
  }
  printf( "\nValor decimal do caracter: %d", decimal );
  getchar();
  return 0;
}

N.B.

  • '0' and 0 are differents
  • > (greater) and >= (greater or equal) have different meaning