binary data to a std::string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vermarajeev
    New Member
    • Aug 2006
    • 180

    binary data to a std::string

    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.

    Code:
    int main(int argc, char *argv[])
    {
        ByteArray byteArray;   //is an array of bytes
        ifstream ifs ( "m1_enc.ct", ios::binary );  //binary file    
        if ( !ifs.is_open () )
              { 
                     return -1;
              }    
        while( !ifs.eof() )
        {
            //read binary data from file and put into byteArray
        }
        ifs.close();
        //How to achieve this below code?; something like function toStdString()
        string str = QString(byteArray).toStdString() ; //Unable to achieve
        return 0;
    }
    Thanks
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    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: http://www.qtforum.org/

    I can tell you that [CODE=cpp] while( !ifs.eof() )[/CODE] 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 http://www.cplusplus.com/reference/i...m/ios/eof.html. 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.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Use the power of the C++ Standard LIbrary. A stringstream can help you out.

      [code=cpp]
      unsigned int var = 1234;
      bitset<32> b(var);
      stringstream ss;
      ss << b;
      string str;
      ss >> str;
      cout << str << endl;
      [/code]

      Comment

      Working...