c++ - 二进制字符串到 C++ 中的 byte[]?

标签 c++ string qt byte

我实际上在 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
{
    //?????
}

感谢您的回复。

最佳答案

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 写过一行)

关于c++ - 二进制字符串到 C++ 中的 byte[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10037612/

相关文章:

C++ 如何将成员函数指针传递给另一个类?

c++ - 插入到排序位置链表

c++ - 为什么 pA、pB、pC 不相等?

java - 如何创建一个组合两个变量的变量?

java - Java中如何获取和使用next String

C 中凯撒代码的结果附加字母

c++ - 如何将 QSizeGrip 放在 QDial 的右下角?

android - Qt/C++ 的跨平台移动通知?

c++ - 如何使用 Qt QwtPlot3D 可视化数据

c++ - Qt:.pro 文件丢失?