By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,826 Members | 2,443 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,826 IT Pros & Developers. It's quick & easy.

binary data to a std::string

P: 180
How to convert a byte array to a std::string. Byte array contains bytes of data.
See the code below. Help me to write toStdString() function defined in ByteArray class.

Expand|Select|Wrap|Line Numbers
  1. int main(int argc, char *argv[])
  2. {
  3.     ByteArray byteArray;   //is an array of bytes
  4.     ifstream ifs ( "m1_enc.ct", ios::binary );  //binary file    
  5.     if ( !ifs.is_open () )
  6.           { 
  7.                  return -1;
  8.           }    
  9.     while( !ifs.eof() )
  10.     {
  11.         //read binary data from file and put into byteArray
  12.     }
  13.     ifs.close();
  14.     //How to achieve this below code?; something like function toStdString()
  15.     string str = QString(byteArray).toStdString() ; //Unable to achieve
  16.     return 0;
Aug 14 '07 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 671
Did you mean QByteArray, which is part of Trolltech's QT? Because you use QString, which is. Since you are effectively asking a question on how to use a third party library, ask your question on forums that are dedicated to it. Here's a google search result:

I can tell you that
Expand|Select|Wrap|Line Numbers
  1.  while( !ifs.eof() )
won't work. Your logic is something like, while you haven't reached the end of the file, keep reading from the file. But eof doesn't check if you have reached the end of the file. Take a look at Eof returns true only when eofbit is set. And eofbit is set only after a failed I/O attempt. But your code does it the other way around. It checks for eof bit first, and then attempts I/O (which could then fail). See the problem?

You realize that you can test an attempt at file input itself? All those I/O operations have return values as well.
Aug 14 '07 #2

Expert Mod 5K+
P: 9,197
Use the power of the C++ Standard LIbrary. A stringstream can help you out.

Expand|Select|Wrap|Line Numbers
  1. unsigned int var = 1234;
  2.     bitset<32> b(var);
  3.     stringstream ss;
  4.     ss << b;
  5.     string str;
  6.     ss >> str;
  7.     cout << str << endl;
Aug 14 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.