c++ - 无法将 1 和 0 的字符串写入二进制文件,C++

标签 c++ binary

我有一个函数,它接收一个指向字符串的指针,该字符串的名称为要打开的文件,并用 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();
}

最佳答案

After writing to binary file I have exactly the same...

我想你想转换 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>>() 填充和 std::istringstream例如。

关于c++ - 无法将 1 和 0 的字符串写入二进制文件,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22591429/

相关文章:

linux - 我需要一个 Win/Linux 的二进制比较工具

java - 在JAVA中,将图像的RGB值转换为二进制值的最快方法是什么?

recursion - Prolog 二进制加法

c++ - 函数A调用函数B,函数B调用函数A,你怎么调用它?

c++ - tableView数据更改后将数据保存到数据库中

c++ - 自动功能必须在使用前定义

Java从很长的范围内获取位范围

c++ - 将变量(float *)保存到 plhs

c++ - const string 类成员的初始化列表

java - System.out.println() 如何处理二进制数据?