1

我实际上在 Qt 中使用 QString 。所以如果有一个简单的功能请告诉我:)

我正在考虑将二进制字符串逐字节存储到文件中:

QString code = "0110010101010100111010 /*...still lots of 0s & 1s here..*/";
ofstream out(/*...init the out file here...*/);
for(; code.length() / 8 > 0; code.remove(0, 8))    //a byte is 8 bits
{
    BYTE b = QStringToByte(/*...the first 8 bits of the code left...*/);
    out.write((char *)(&b), 1);
}
/*...deal with the rest less than 8 bits here...*/

我应该如何编写我的 QStringToByte() 函数?

BYTE QStringToByte(QString s)    //s is 8 bits
{
    //?????
}

感谢你的回复。

4

2 回答 2

1

QString 有一个不错的toInt方法,它可以选择将基数作为参数(在您的情况下为基数 2)。只需剥离 8 个字符以形成一个新的 QString,然后执行str.toInt( &somebool, 2 ).

如果没有错误检查,它可能是:

BYTE QStringToByte(QString s)    //s is 8 bits
{
  bool ok;
  return (BYTE)(s.left( 8 ).toInt( &ok, 2 ));
}

(不过不要相信我的话,我一生中从未在 Qt 中写过一行)

于 2012-04-06T00:00:37.747 回答
0

您可以尝试boost::dynamic_bitset将位写入文件。

void write_to_file( std::ofstream& fp, const boost::dynamic_bitset<boost::uint8_t>& bits )
{
     std::ostream_iterator<boost::uint8_t> osit(fp);
     boost::to_block_range(bits, osit);
}
于 2012-04-06T00:03:02.117 回答