Nothing is ready.
In fact to do something production ready needs to deal with a lot, analyze endianess , etc. Something naive not universal would be this:
#include <stdio.h>
#include <stdlib.h>
void BinFormat(char character, char *text) {
text[8] = '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'
';
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);
}
See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .
The strategy of how to allocate memory can vary. I do not really like to allocate in heap , but it's the simplest and most correct.
Because C has the incredible shortcoming of not being able to return an array , it could return a struct
with 8 or 9 chars
, but would then require a cast to transform into a real string .
Depending on the case you could have all the printable characters (95) in a static table, it would occupy 855 bytes, but would have the advantage of being very fast. But something more universal would require more memory.
No good solution.
So is it a more readable solution?
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
See running ideone . Also put it in GitHub for future reference .
Let's now leave more C:
#include <stdio.h>
#include <stdlib.h>
void BinFormat(char character, char *text) {
text[8] = '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'
';
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);
}