How to transform a decimal number to binary using String

Asked

Viewed 193 times

0

Well I managed using whole numbers, only the teacher wants code to accept very large number that do not fit in whole, he said he had to read as a string, only I do not know how this can be done

My code using integer numbers

#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;
}
  • http://www.programsprontos.com/algorithmos-converters/conversao-decimal-parabinario-c/ Here an article for you

  • A long is acceptable? It has to be string really? It’s a lot more work.

  • hello cool so he went through with String, he said it’s a super challenge

1 answer

1


use the function sprintf(), 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';
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.