Decimal to Binary

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

    For 31 values, instead of doing malloc to allocate a string, followed by the bit manipulation to fill it, you may just want to use a lookup table.

    static const char *bitstrings[] = {
        "00000", "00001", "00010", … "11111"
    };
    

    Then your conversion is as simple as return bitstrings[i]. If you're doing this often, this will be faster (by avoiding malloc).

    Otherwise, you don't really need any shifting (except to make writing your constants easier); you can just use bit-and:

    char *bits = malloc(6);
    bits[0] = (i & (1<<4)) ? '1' : '0';   /* you can also just write out the bit values, but the */
    bits[1] = (i & (1<<3)) ? '1' : '0';   /* compiler should be able to optimize a constant!     */
    ⋮
    bits[6] = 0; /* null-terminate string*/
    

    There is a (maybe) micro-optimization you can do if you assume ASCII, by using addition. You can also use a loop here, but I needed two lines for the comment :-P. Performance-wise, neither will matter. All the time is spent in malloc.

提交回复
热议问题