【问题标题】:Outputting a Binary String to a Binary File in C++在 C++ 中将二进制字符串输出到二进制文件
【发布时间】:2015-11-01 00:15:46
【问题描述】:

假设我有一个字符串,其中包含一个像“0110110101011110110010010000010”这样的二进制文件。有没有一种简单的方法可以将该字符串输出到二进制文件中,以便该文件包含 0110110101011110110010010000010?我知道计算机一次写入一个字节,但我无法想出一种将字符串的内容作为二进制文件写入二进制文件的方法。

【问题讨论】:

  • 首先您必须将字符串转换为二进制数据。然后,将该数据写入文件。顺便说一句,您的字符串不会完美地映射到文件,因为它没有正确的位数

标签: c++ binaryfiles binary-data


【解决方案1】:

使用位集:

//Added extra leading zero to make 32-bit.
std::bitset<32> b("00110110101011110110010010000010");

auto ull = b.to_ullong();

std::ofstream f;
f.open("test_file.dat", std::ios_base::out | std::ios_base::binary);
f.write(reinterpret_cast<char*>(&ull), sizeof(ull));
f.close();

【讨论】:

    【解决方案2】:

    我不确定这是否是您需要的,但您可以这样做:

    #include<iostream>
    #include<fstream>
    #include<string>
    using namespace std;
    int main() {
        string tmp = "0110110101011110110010010000010";
        ofstream out;
        out.open("file.txt");
        out << tmp;
        out.close();
    
    }
    

    【讨论】:

    • 不幸的是,这不是我想要的。您的输出将是文本格式,相当于二进制格式的输出将是 0x30313130 ..... 我正在寻找的是包含二进制 0110110101011110110010010000010 的文件。希望我在那里说得通。
    • 如果你运行上面的代码,文件file.txt将包含0110110101011110110010010000010。你是什么意思?
    • @waterisawesome:你可以看看我的方法
    • 他希望文件中的二进制数据是这样的,而不是恰好是“0”和“1”的字符序列
    【解决方案3】:

    确保您的输出流处于二进制模式。这可以处理字符串大小不是字节中位数的倍数的情况。额外的位设置为 0。

    const unsigned int BitsPerByte = CHAR_BIT;
    unsigned char byte;
    for (size_t i = 0; i < data.size(); ++i)
    {
        if ((i % BitsPerByte) == 0)
        {
            // first bit of a byte
            byte = 0;
        }
        if (data[i] == '1')
        {
            // set a bit to 1
            byte |= (1 << (i % BitsPerByte));
        }
        if (((i % BitsPerByte) == BitsPerByte - 1) || i + 1 == data.size())
        {
            // last bit of the byte
            file << byte;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 2016-08-30
      相关资源
      最近更新 更多