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

1

My code works to a certain extent. When I supply values above 1023 to num, the program goes wrong, below 1023 the program works perfectly. Does anyone know what it 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;
}
    
asked by anonymous 20.03.2018 / 21:59

1 answer

1

It happens that since you are saving the binary representation in an integer, it quickly passes the representation capacity of it and generates an overflow .

Look at the number 1200 in binary:

10010110000

See the same integer number, visually formatted for easy 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, such as 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 the code working on Ideone

Alerte, however, will have the same problem if you try to convert numbers a little larger, such as 1000000 , because the binary representation grows too fast. To work around this problem just by saving the representation in string , which can be as large as you want.

    
21.03.2018 / 00:13