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
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