Following my earlier question. Is there a way to write a string in a compressed/bit version using C++ native idiom. I am thinking something like Perl’s native pack and unpack.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Based on reading your previous question, I think you mean to say that you want a binary encoded output, rather than a ‘compressed’ output. Generally, ‘compressed’ is used to refer specifically to data that has been reduced in size through the application of an algorithm such as LZW encoding. In your case, you may find that the output is ‘compressed’ in the sense that it is smaller because for a wide variety of numbers a binary representation is more efficient than an ASCII representation, but this is not ‘compression’ in the standard sense, which may be why you are having trouble getting the answer you are looking for.
I think you are really asking the following:
Given a number in ASCII format (stored in a std::string, for example), how can I write this to a file as a binary encoding integer?
There are two parts to the answer. First, you must convert the ASCII encoded string to an integer value. You may use a function such as strtol, which will return a long integer equivalent in value to your ASCII encoded number. Do be aware that there are limitations on the magnitude of the number that may be represented in a long integer, so if your numbers are very, very large, you may need to be more creative in translating them.
Second, you must write the data to the output stream using ostream::write(), which does not attempt to format the bytes you give it. If you simply use the default operator<<() stream operation to write the values, you’ll find that your numbers just get translated back to ASCII and written out that way. Put this all together like this: