给出前16和3935输出没有响应是给我数不是二进制

时间:2016-10-04 13:27:54

标签: c

#include <stdio.h>
#include <math.h>

long long convertToBinary(int dnumber);

int main() {

    int width;
    int dnumber;
    printf("Enter Width(int bits): ");
    scanf("%d",&width);
    printf("\nEnter Decimal NUmber: ");
    scanf("%d",&dnumber);

    if(width==8)
    {
        if(dnumber<=255 && dnumber>0)
        {
            printf("\nOutput - U2B(%d) = %lld",dnumber,convertToBinary(dnumber));
        }else{
            printf("You entered bigger than 8 bits");
        }
    }else if(width==16){

        if(dnumber<=65535 && dnumber>255){
           printf("\nOutput - U2B(%d) = %lld",dnumber,convertToBinary(dnumber));
        }else{
            printf("You entered lower or bigger number than 16 bits");
        }
    }
    return 0;
}

long long convertToBinary(int dnumber){

    long long binaryNumber = 0;
    int remaindr, i = 1;

    while (dnumber!=0)
    {
        remaindr = dnumber%2;
        //printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", i++, dnumber, remaindr, dnumber/2);
        dnumber /= 2;
        binaryNumber += remaindr*i;
        i *= 10;
    }
    return binaryNumber;
}
  • 当我给出8和255它给我二进制
  • 当我给16和3935时,它给我十进制

为什么它必须给我二进制数?

1 个答案:

答案 0 :(得分:2)

iconvertToBinary

中溢出

将类型更改为long long:

long long i = 1;