Decimal to Binary

后端 未结 12 1341
攒了一身酷
攒了一身酷 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:29

    #include 
    #include 
    
    char numstr[9024];
    int i = 0;
    
    void format(int n, int base);
    void printreverse(char *s);
    
    int main()
    {
         int testnum = 312;    // some random test number
         format(testnum, 2);   // 2 for binary
         printreverse(numstr);
         putchar('\n');
    
         return 0;
    }
    
    void format(int n, int base)
    {
        if (n > 0) {
            char tmp = (n % base) + '0';
            numstr[i++] = tmp;
    
            // If we put this above other two we don't need printreverse,
            // But then we will have unwanted results in other places of numstr if we can't reset it
    
            format(n/base, base); 
        } else
            numstr[i] = '\0'; // terminating character
    }
    
    void printreverse(char *s)
    {
        long len = strlen(s);
        while (len-->0)
            putchar(s[len]);
    }
    

提交回复
热议问题