Decimal to Binary

后端 未结 12 1320
攒了一身酷
攒了一身酷 2020-12-01 13:08

I have a number that I would like to convert to binary (from decimal) in C.

I would like my binary to always be in 5 bits (the decimal will never exceed 31). I alrea

12条回答
  •  醉酒成梦
    2020-12-01 13:49

    Here is C program to convert decimal to binary using bitwise operator with any decimal supported by system and holding only the required memory

    #include 
    #include 
    #include 
    int main (int argc, char **argv) 
    {
        int n, t = 0;
        char *bin, b[2] = ""; 
        scanf("%d", &n);
        bin = (char*)malloc(sizeof(char) + 2);
        while (n != 0)
        {
            t = n >> 1;
            t = t << 1;
            t = n - t;
            n = n >> 1;
            itoa(t, b, 10);
            bin = realloc((char*)bin, sizeof(char) + 1);
            strcat(bin, b);
        }
        strrev(bin);
        printf("\n%s\n", bin);
    
        return 0 ;
    }
    

提交回复
热议问题