【问题标题】:Can't write string of 1 and 0 to binary file, C++无法将 1 和 0 的字符串写入二进制文件,C++
【发布时间】:2014-03-24 03:20:33
【问题描述】:

我有一个函数,它接收一个指向要打开的文件名的字符串的指针,并用 1 和 0 进行编码; codedLine 包含类似 010100110101110101010011 的内容 写入二进制文件后,我完全一样......你会推荐吗?谢谢。

    void codeFile(char *s)
{
    char *buf = new char[maxStringLength];
    std::ifstream fileToCode(s);
    std::ofstream codedFile("codedFile.txt", std::ios::binary);
    if (!fileToCode.is_open())
        return;
    while (fileToCode.getline(buf, maxStringLength))
    {
        std::string codedLine = codeLine(buf);
        codedFile.write(codedLine.c_str(), codedLine.size());
    }
    codedFile.close();
    fileToCode.close();
}

【问题讨论】:

  • 你到底在问什么?
  • 问题是我不能将例如 101010101 的字符串写成二进制

标签: c++ binary


【解决方案1】:

写入二进制文件后,我有完全相同的...

我想您想将 std::string 输入转换为其二进制等效项。

您可以使用std::bitset<> 类将字符串转换为二进制值,反之亦然。将字符串直接写入文件会导致字符值'0''1' 的二进制表示。

一个如何使用它的例子:

std::string zeroes_and_ones = "1011100001111010010";
// Define a bitset that can hold sizeof(unsigned long) bits
std::bitset<sizeof(unsigned long) * 8> bits(zeroes_and_ones);

unsigned long binary_value = bits.to_ulong();

// write the binary value to file
codedFile.write((const char*)&binary_value, sizeof(unsigned long));

注意
上面的示例适用于 标准。对于早期版本,std::bitset 不能直接从字符串初始化。但它可以使用operator&gt;&gt;()std::istringstream 来填充。

【讨论】:

  • @Eugene 抱歉,我的示例中还有另一个小缺陷。查看std::bitset&lt;sizeof(unsigned long) * 8&gt;的定义!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-12
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 2017-06-06
  • 1970-01-01
  • 2020-08-28
相关资源
最近更新 更多