#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时,它给我十进制数
为什么一定要给我二进制数?

最佳答案

i溢出
将类型更改为long long:

long long i = 1;

09-26 11:21