My guess is there is nothing wrong with writing binary data to a text file. The flaw is letting NOTEPAD or whatever display the data and interpreting it as ASCII. Hence the garbage appearance. If your encode / decode is correct, you should be able to retrieve the correct data from the file regardless of how garbagey it looks in the screen.