Decimal to Binary

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

    My take:

    char* to_bitstring(uint32_t val, char buffer[], int size) {
        buffer[--size] = 0;
        while (size > 0) {
            buffer[--size] = (val % 2 ? '1' : '0');
            val = val >> 1;
        }
    
        return buffer; /* convenience */
    }
    

    This will write SIZE characters to BUFFER:

    char buffer[17];
    printf("%s\n", to_bitstring(42, buffer, sizeof(buffer)));
    

    And will print:

    0000000000101010
    

提交回复
热议问题