2

I am currently attempting to store a string containing binary code.

When I attempt to write this string to a text file it simply stores each 0 and 1 character in a string format, rather than storing it into 8 bit chunks as I require. This causes the file to be larger than intended, considering it uses 8 bits to store each 0 and 1.

Should I write the string to a .bin file instead of a .txt file? If so how would I go about doing this, and if possible an example with some working code.

My thanks for any advice in advance.

   string encoded = "01010101";    
   ofstream myfile;   
   myfile.open ("encoded");   
   myfile <<  encoded;   
   myfile.close();   

Clarification: I have a string made up of 1's and 0's(resulting from a Huffman Tree), I wish to break this string up into 8 bit chunks, I wish to write each character represented by said chink to a compressed file.

2
  • Do you have a good reason for storing binary data in strings? Can't use something meant for storing binary data? Commented Mar 23, 2013 at 14:22
  • I am attempting to store binary resulting from encoding text through the use of a Huffman tree. The issue I am having is writing the binary to a file in a 8 bit compressed manner. Commented Mar 23, 2013 at 15:00

3 Answers 3

1

std::bitset can convert a string to an integer.

std::bitset<8> bits("01010101");
cout << bits.to_ullong();
Sign up to request clarification or add additional context in comments.

Comments

1

I'm only guessing since you don't show any code, but it seems you have a string containing the characters '1' and '0'. If you write that to a file of course it will be as a text. You need to convert it to integers first.

See e.g. std::stoi or std::strtol for functions to convert strings of arbitrary base to integers.

Comments

0

Should I write the string to a .bin file instead of a .txt file?

If you wish so... But that wouldn't make a difference either. ofstream doesn't care about filenames. Just convert the string to a byte (uint8_t) and write that byte to the file:

string s = "10101010";
uint8_t byte = strtoul(s.c_str(), NULL, 2);
myfile << byte;

2 Comments

Like so? string test = "01010101"; uint8_t byte = strtoul(test.c_str()); ofstream myfile3; myfile3.open ("binary.txt"); myfile3 << test; myfile3.close(); @H2CO3
@user2202417 Yes, except that I accidentally left out two arguments of strtoul. See edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.