Reputation: 2356
I'm using QString in Qt actually. So if there's a straightforward function please tell me:)
What I'm thinking of doing is storing a binary string into a file byte by byte:
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...*/
How should I write my QStringToByte() function?
BYTE QStringToByte(QString s) //s is 8 bits
{
//?????
}
Thank you for your reply.
Upvotes: 1
Views: 1858
Reputation: 2344
You may try boost::dynamic_bitset
to write bits to a file.
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);
}
Upvotes: 0
Reputation: 57555
QString has a nice toInt method, that optionally takes the base as a parameter (in your case base 2). Just strip 8 characters to form a new QString, and do str.toInt( &somebool, 2 )
.
With no error checking it would be probably:
BYTE QStringToByte(QString s) //s is 8 bits
{
bool ok;
return (BYTE)(s.left( 8 ).toInt( &ok, 2 ));
}
(don't take my word for it though, never wrote a line in Qt in my life)
Upvotes: 1