There is nothing ready.
In fact to do something Production ready need to handle a lot of things, analyze the endianess, etc. Something naive not universal would be this:
#include <stdio.h>
#include <stdlib.h>
void BinFormat(char character, char *text) {
text[8] = '\0';
for (int i = 7; i >= 0; i--) text[i] = ((character >> i) & 1) + '0';
}
int main(void) {
char *text = malloc(9);
BinFormat('A', text);
printf("%s\n", text);
BinFormat('B', text);
printf("%s\n", text);
BinFormat('C', text);
printf("%s\n", text);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
The strategy of how to allocate memory may vary. I don’t really like to allocate to heap, but it is the simplest and correct.
As C has the incredible disability of not being able to return one array, could return a struct
with 8 or 9 chars
, but then it would require a cast to turn into a string real.
Depending on the case it could have all printable characters (95) in a static table, it would take 855 bytes, but it would have the advantage of being very fast. But something more universal would require more memory.
There’s no good solution.
This is a more readable solution?
int divisor = (int)pow(2, i); //base 2 elevado à posição que está para achar o divisor
printf("[%d, ", divisor);
int cabe = character / divisor; //acha quantas unidades cabem no divisor
printf("%d, ", cabe);
int impar = (cabe % 2 != 0); //o que cabe é impar?
printf("%d] ", impar);
text[i] = impar + 48; //avança na tabela ASCII 48 posições para chegar em '0' ou '1'
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Let’s now leave more C:
int divisor = i; //base 2 elevado à posição que está para achar o divisor
printf("[%d, ", divisor);
int cabe = character >> i; //acha quantas unidades cabem no divisor
printf("%d, ", cabe);
int impar = cabe & 1; //o que cabe é impar?
printf("%d] ", impar);
text[i] = impar + '0'; //avança na tabela ASCII até o '0' ou '1' se for 0 ou 1
Note: On Soen has an example with
itoa
, but I should warn you that this is not standard, so it might not work on some compilers, in case someone comes up with an answer about this.– Guilherme Nascimento