Search code examples
c++serializationsstream

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

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).