ASCII treats digits as just other symbols, the same as letters. They have their own numeric values that
are not the same as the numeric value of the digit. For example, a char that represents the symbol '0', interpreted as an integer value, is actually the value 48.
For your purposes, you probably
do not want to try to make the output look like a digit, because then you can only count up to 9. Instead, just write the run length as a byte, and accept the fact that in general, it will look (when interpreted as text) like some weird symbol.
So "abcdefffff" gets encoded as '<byte with value 5>' 'a' 'b' 'c' 'd' 'e' '<byte with value 0>' '<byte with value 5>' 'f'. You decode that as follows:
- Read a byte.
- It's not zero, so we read the corresponding number of non-run bytes.
- Read a byte.
- This time it is zero, so read the next two bytes.
- The first byte has value 5 (NOT a representation of the digit '5'), and the second byte is the symbol 'f', so output 'f' 5 times.
Thus our decoder has to look like:
While (non_run_count <- byte from encoded data): If non_run_count is zero: run_count <- byte from encoded data. run_symbol <- byte from encoded data. Do run_count times: emit run_symbol. Else: Do non_run_count times: emit byte from encoded data.
Right now you're not reading run_symbol or doing anything with it, just leaving it for the next time through the loop. You're not even decrementing the size counter there, which causes other problems.
Do not try to handle files by any technique involving counting their length ahead of time. This way lies pain and misery. Instead, just process the data until you run out. This can be done in a simple and idiomatic way: just use the read operation as the condition for your while loop.
Also, why are you using the variable 'n' to hold the constant 0? And why are you testing compressed[j] and then outputting data from compressed[x]?