The text to binary converter takes text as input and produces binary code as output. Here you can try to convert some text. Later we will see how it works and you can try to do the example program in C.
Separate with spaces
To "decode" that back to text, use the binary to text converter.
We need to take the code of each character in decimal and convert it to binary. The input is basically a string, so taking each character from it is no problem. Reading the decimal code of a character is also a “one liner”. To do the conversion of that code to binary, we will use the function that we created in the decimal to binary lesson.
If you want to do the text to binary by hand, you don't need to do the decimal to binary. You can use the direct mapping of a symbol to binary. To make it easier I prepared several tables with the binary alphabet.
We use up to 8 binary digits to represent the binary code. This limits the number of characters that we can represent to 256. Thus we will convert only ASCII text (unicode and other encodings that can represent thousands of symbols are not suitable for this example).
The complete code of the example is available for free download from here: text-to-binary.zip
We start by reading up to 100 symbols from the standard input. We don't want to stop reading when the scanner “sees” a whitespace (including space). We explicitly instruct scanf to read until the first new line character, using the special format [^\n].
We want to format the output for easy reading, by inserting a space after each binary byte. For that reason we allocate 8 + 1=9 binary elements for each symbol from the input text.
What remains to be done is to:
Taking each character from a string is trivial – we just dereference the pointer:
In C if we don't specify otherwise, the char is just a
number. So extracting the decimal code is just as trivial. I
explain the decimalToBinary function in the decimal to binary lesson.
So all you need is, to understand how the pointers work, the rest is easy as pie ;)
Several notes for the new guys: