Search code examples
c++filebinarybinaryfiles

Write real binary to file


I am currently working on a project to read binary data from a file do stuff with it and to write it back again. The reading works well so far, but when I try to write the binary-data stored in a string to a file, it writes the binarys as text. I think it has soemthing to do with the opening mode. Here is my code:

void WriteBinary(const string& path, const string& binary)
{
    ofstream file;
    file.open(path);
    std::string copy = binary;
    while (copy.size() >= 8)
    {
        //Write byte to file
        file.write(binary.substr(0, 8).c_str(), 8);
        copy.replace(0, 8, "");
    }
    file.close();
}

In the function above the binary parameter looks like this: 0100100001100101011011000110110001101111


Solution

  • With the help of "aschelper" I was able to create a solution for this problem. I converted the binary string to its usual representation, before writing it to the file. My code is below:

    // binary is a string of 0s and 1s. it will be converted to a usual string before writing it into the file.
    void WriteBinary(const string& path, const string& binary)
    {
        ofstream file;
        file.open(path);
        string copy = binary;
    
        while (copy.size() >= 8)
        {
            char realChar = ByteToChar(copy.substr(0, 8).c_str());
            file.write(&realChar, 1);
            copy.replace(0, 8, "");
        }
        file.close();
    }
    
    
    // Convert a binary string to a usual string
    string BinaryToString(const string& binary)
    {
        stringstream sstream(binary);
        string output;
        while (sstream.good())
        {   
            bitset<8> bits;
            sstream  >> bits;
            char c = char(bits.to_ulong());
            output += c;
        }
        return output;
    }
    
    // convert a byte to a character
    char ByteToChar(const char* str) {
        char parsed = 0;
        for (int i = 0; i < 8; i++) {
            if (str[i] == '1') {
                parsed |= 1 << (7 - i);
            }
        }
        return parsed;
    }