I suppose you need to do your homework, so here is my solution. :)
I was just trying to write an ascii-to-binary + binary-to-ascii to C converter, by coincidence. The binary for ascii was pretty simple with the strtol () function and all, and my code for converting a character (which is practically int) was as follows:
void chartobinf(int c, FILE* out) { size_t n = 8*sizeof(unsigned char); while (n-- > 0) fputs(((c >> n) & 1) ? "1" : "0", out); }
This prints the symbol (change the parameter and type of size according to your needs) in the correct order (which, in my opinion, is the biggest value), unlike many other solutions.
I especially like this solution because it is very short. Then it does not save the value as a string or anything like that.
Edit: I think you can also substitute fputs() call with
fputc(((c >> n) & 1) ? '1' : '0', out);
Maybe microseconds are faster? Dunno.
source share