We show two functions that print the SINGLE character to a binary file.
void printbinchar(char character) { char output[9]; itoa(character, output, 2); printf("%s\n", output); }
printbinchar (10) writes to the console
1010
itoa is a library function that converts a single integer value to a string with the specified base. For example ... itoa (1341, output, 10) will write "1341" in the output line. And of course, itoa (9, output, 2) will write "1001" in the output line.
The following function will print the full binary representation of the character on the standard output, that is, it will print all 8 bits, also if the highest bits are zero.
void printbincharpad(char c) { for (int i = 7; i >= 0; --i) { putchar( (c & (1 << i)) ? '1' : '0' ); } putchar('\n'); }
printbincharpad (10) writes to the console
00001010
Now I present a function that outputs an entire string (without the last null character).
void printstringasbinary(char* s) { // A small 9 characters buffer we use to perform the conversion char output[9]; // Until the first character pointed by s is not a null character // that indicates end of string... while (*s) { // Convert the first character of the string to binary using itoa. // Characters in c are just 8 bit integers, at least, in noawdays computers. itoa(*s, output, 2); // print out our string and let write a new line. puts(output); // we advance our string by one character, // If our original string was "ABC" now we are pointing at "BC". ++s; } }
Note, however, that itoa does not add zero zeros, so printstringasbinary ("AB1") will print something like:
1000001 1000010 110001
Salvatore previti
source share