Search code examples
cansi-c

Fault in decimal to binary in c


#include <stdio.h>

main(){
    printf("Give a number in decimal form\n");
    int Division,a=1,sum=0,Bit,Digit;
    scanf("%d",&Division);
    do{
        Digit= Division%2;
        if (Digit==1){
            sum++;
        }
        Division/=2;
        Bit += Digit*a;
        a*=10;
    }while(Division>0);
    printf("%d is the number in binary form\n",Bit);
    printf("The number of 1s in the binary form is %d",sum);
}

The purpose of the exercise was to transform a decimal number to its binary form and count the 1s on it. It works just fine until 1023, but in 1024 it is printing "binary" numbers containing decimal digits. Note that the 1 count works correctly. Is the problem concerning the range?


Solution

  • When you get to the last (most significant) bit of 1024, the value of a is 10000000000 (10^10). Except it isn't. Because int is a 32-bit integer, the value of a overflows (twice) and ends up being 1410065408.