1

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.

6
  • Out of curiosity, how did you come by a "binary string" in the first place? Commented Apr 5, 2012 at 23:57
  • And did you want to save those 1s and 0s as bits or bytes? Your thought process isn't clear here. Commented Apr 5, 2012 at 23:59
  • @RussellBorogove It is an int array encoded with Huffman. So I've first stored the Huffman frequency table and then I want to save this code. Commented Apr 5, 2012 at 23:59
  • @MooingDuck I want to save them as BYTE. For the binary string I provided, I would first like to save "01100101" as a byte, and then "01010100" as the next byte, and so on Commented Apr 6, 2012 at 0:01
  • 2
    Ah. You are modeling a stream of bits with a stream of ASCII characters. Your life will be better if you write a class or a set of functions to model a stream of bits with a stream of bits packed into an array of bytes or integers. Commented Apr 6, 2012 at 0:03

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Your method works well enough. Thanks! And don't be that pessimistic:)
0

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);
}

2 Comments

@KornelKisielewicz "...and now you have two problems."
@Russel, at least not a ProblemFactory :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.