user2202417
user2202417

Reputation: 33

C++, Storing a String containing binary into a text file

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.

Upvotes: 2

Views: 804

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409364

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.

Upvotes: 1

user529758
user529758

Reputation:

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;

Upvotes: 0

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24153

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

std::bitset<8> bits("01010101");
cout << bits.to_ullong();

Upvotes: 1

Related Questions