I want to make a decimal to binary converter without using itoa() or vectors in C

Asked

Viewed 1,288 times

1

My code works up to a point. When I provide values above 1023 for num, the program goes wrong, below 1023 the program works perfectly. Someone knows what can be?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int bin = 0, num = 0, resp = 0, cont = 0;
    printf("digite um numero\n");
    scanf("%d", &num);
    do
    {
        bin = (bin * 10) + (num % 2);
        num = num / 2;
        cont++;
    }
    while (num > 0);
    do
    {
        cont--;
        resp = (resp * 10) + (bin % 2);
        bin = (bin - (bin % 2)) / 10;
    }
    while (cont > 0);
    printf("%d", resp);
    return 0;
}
  • 1

    You can select the code and press <ctrl> + k to format the code properly

  • Thanks for the info! I made the changes already.

  • You can take a look at this solution: Decimal to Binary in C that stores the value in a string.. or simply print to the screen (depending on your need)

  • I get it. I wanted to use only the basic operations, but I will consider using it as a solution. Thank you very much!

  • Interesting reading about the transformation to binary: https://answall.com/a/267825/64969; supposedly this answer should be very basic and explained, only needing to understand recursion.

1 answer

1

It turns out that since it is storing the binary representation in an integer, it quickly passes the capacity of representation of it and generates a overflow.

Note the number 1200 in binary:

10010110000

See the same number in integer, visually formatted to simplify reading:

10,010,110,000

That’s 10 billion, and clearly out of the range of integers that goes up to 2,147,483,647.

So the only thing you need to do is change the type to one with more representation, like the unsigned long long:

int main()
{
    unsigned long long bin = 0, num = 0, resp = 0, cont = 0;
    printf("digite um numero\n");
    scanf("%lld", &num); //tipo lld
    ...
    printf("%lld", resp); //tipo lld
    return 0;
}

See code working on Ideone

Warning that however, you will have the same problem if you try to convert slightly larger numbers such as 1000000, because the binary representation grows too fast. To get around this problem only keeping the representation in a string, that can be as big as you want.

  • I just tested it. It worked fine. I thought the error might actually be because of the same overflow, but I didn’t know how to fix it. Thank you very much! To do with string, I would have to use vectors, right?

  • @Lucas Sim with string would be using vectors

  • Oh yes, but I think that the proposed exercise can not be done with vectors, I think that the teacher would not allow. But even so, I will look for how to make this solution with string. Again thank you!

Browser other questions tagged

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