How to transform a number from decimal to binary using String

0

Well I managed using integers, but the teacher wants to accept code that is too large that does not fit in the integer, it said it had to read as a string, but I do not know how this can be done. >

My code using integers

#include <stdio.h>

int main(int argc, char** argv)
{
   int num, aux, vetor[90], i = 0;

   scanf("%d", &num);
   while(num >= 1)
   {
     aux = num;
     num = num / 2;
     aux = aux % 2;
     vetor[i++] = aux;
   }
   for(int j = i - 1; j >= 0; j--)
   {
      printf("%d", vetor[j]);
   }
   putchar('\n');
   return 0;
}
    
asked by anonymous 29.04.2018 / 15:52

1 answer

1

use the sprintf () function, using the table values ASCII :

#include <stdio.h>

int main(int argc, char** argv)
{
   int num, aux, i = 0;
   char vetor[200];

   scanf("%d", &num);
   while(num >= 1)
   {
     aux = num;
     num = num / 2;
     aux = aux % 2;
     sprintf(&vetor[i++],"%c",aux+'0');
   }
   for(int j = i - 1; j >= 0; j--)
   {
      printf("%c", vetor[j]);
   }
   putchar('\n');
   return 0;
}

or, more simply, just convert the numeric value to encoding ASCII :

while(num >= 1)
{
    aux = num;
    num = num / 2;
    aux = aux % 2;
    vetor[i++] = aux+'0';
}
    
05.05.2018 / 15:58