[英]Binary string to byte[] in C++?
我實際上在 Qt 中使用 QString。 所以如果有一個簡單的 function 請告訴我:)
我想做的是將二進制字符串逐字節存儲到文件中:
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() function?
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 中寫過一行)
您可以嘗試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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.