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