Binary conversion limit in C

2

I developed this code in C to convert integers to binary, but the limit is 1023. Any number above that, conversion is no longer performed

What is the possible reason for this?

int binario(int num) {

    if (num == 0)
        return 0;
    return (num % 2) + 10 * binario(num / 2);

}

int main(){

    printf("%d",binario(7));
}
    
asked by anonymous 15.02.2017 / 23:10

1 answer

5

The problem is that it is returning a int that has a limited capacity. I've changed the code to use long which will allow larger numbers. But there is a limit too.

So what's the problem? Try to make a numeric representation as if it were a number. The number is the number, you make accounts with it. The numerical representation is what you see written. It's a text that happens to have numeric digits written, but that's not a number.

You do not account for representations. And showing the number in binary is just a representation. Just like what you see on the screen is usually just a decimal representation.

If you really want to create a binary representation, generate a text and not a number, change the return to char * , and code appropriately to generate the text. As was done in another question .

#include <stdio.h>

long binario(int num) {
    if (num == 0)
        return 0;
    return (num % 2) + 10 * binario(num / 2);
}

int main() {
    printf("%ld", binario(1025));
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
15.02.2017 / 23:24