Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: serialization using sstream

I am testing a serialization code below, which fails for a few numbers. Any idea?

#include <iostream>
#include <sstream>


int main()
{
   std::stringstream ss;

   for (unsigned int m = 0; m < 101; ++m)
   {
      ss.clear();

      unsigned int t = m;

      for (unsigned int i = 0; i < 4; ++i)
      {
         unsigned char c = t;
         ss << c;
         t >>= 8;
      }

      unsigned int n = 0;

      for (unsigned int i = 0, j = 0; i < 4; ++i, j += 8)
      {
         unsigned char c;
         ss >> c;
         n = n | (c << j);
      }

      if (n != m)
         std::cout << "not working for " << m << std::endl;
   }
}

This is the results.

not working for 9
not working for 10
not working for 11
not working for 12
not working for 13
not working for 32

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Take a moment and stare at the "non-working" values. If you stare at them, long enough, they will suddenly look very, very familiar.

You will note that all of them correspond to whitespace characters, in the ASCII table: NL, CR, FF, VT, and the most favorite character of mine: SP, the space character, ASCII code 32 (I think I missed one, I’m just too lazy to look it up…)

>>, on a stream, automatically discards all whitespace characters. If your goal is to read and write individual char values, to streams, you don’t want to use << and >>. You want to use read() and write() methods.

(well, you could probably use <<, but to be consistent, just use read and write).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading