Search code examples
text-filesasciibinaryfilescompression

Is it possible to convert 16bit binary number to two characters and save it to text file?


I want to save some information to a text file(.txt format). To reduce the file size, I use each bit of a 16 bit binary number to represent some information. For example,for a 16 bit binary number0000 0001 1000 1111, each bit has its specific meaning. Since any ASCII character is equal to 8 bit binary number, so I want to convert my 16 bit number to two characters and save it:

uint16_t a;
a = 13 << 10 | 1 << 3 | 2;// a is a 16bit binary number
char b, c;
b = (char)(a>>8);
c = (char)a;// convert a to two characters

Then I will save b and c to a text file. When I read the text file later, I will convert these two characters to 16 bit binary number and get the information. The problem is that I know some ASCII character are not printable, so I wonder to know if there is any problem? Any answer will be much appreciated!


Solution

  • It shouldn't be a problem. Whether a file is text or binary or whatever is just a convention. It all depends on how the program interprets the data. A non-unicode aware text editor will display gibberish when you open a UTF-32 encoded text file, even though the data is "text". Similarly with your program. You can name the file with .jpg and as long as your program knows how to handle it it should be alright.

    Just be sure to read and write it in binary mode. Some programming languages do small amounts of processing for "text mode", such as replacing a newline with the platform's newline.