To practice my C, I've written a small function in C to display an integer as an 8-bit binary number. Please let me know how to improve this function, and other C-style coding conventions. Thanks!
/**
* Converts an integer to binary.
*
* @param num Integer to convert.
*
* @return c-string.
**/
const char* to_binary(int num) {
static char binary[10];
binary[0] = '0';
binary[1] = 'b';
int value = 128;
int number = num;
for (int i = 2; i < 10; i++) {
if (number - value >= 0) {
binary[i] = '1';
number = number - value;
} else {
binary[i] = '0';
}
value = value / 2;
}
return binary;
}
And here's how you call it:
int main() {
const char* result = to_binary(146);
printf("%s\n", result);
}