【问题标题】:Write real binary to file将真正的二进制文件写入文件
【发布时间】:2021-05-17 02:10:55
【问题描述】:

我目前正在从事一个项目,以从文件中读取二进制数据并对其进行处理并再次将其写回。到目前为止,读取效果很好,但是当我尝试将存储在字符串中的二进制数据写入文件时,它会将二进制文件作为文本写入。我认为这与开放模式有关。 这是我的代码:

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();
}

在上面的函数中,binary 参数如下所示:0100100001100101011011000110110001101111

【问题讨论】:

  • 所以大概这正是 binary 对象中的内容:01 文本字符的序列。
  • 是的,但是假设我有问题中提到的二进制字符串并将其写入具有问题中显示的函数的文件,该文件将不包含Hello,这就是字符串在 ascii 中的意思。这只是数字。
  • 如果要将Hello写入文件,则需要将该二进制字符串转换为字节Hell、@987654334 @.
  • 我刚刚尝试了您的解决方案,它确实有效。因此,我使用了this 帖子中描述的 yasen 功能。谢谢

标签: c++ file binary binaryfiles


【解决方案1】:

在“aschelper”的帮助下,我能够为这个问题创建一个解决方案。在将二进制字符串写入文件之前,我将其转换为通常的表示形式。我的代码如下:

// 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2017-06-30
    • 1970-01-01
    • 2015-02-15
    相关资源
    最近更新 更多