title: C++ read binary file and convert to hex
body: <p>I'm having some problems reading a binary file and converting it's bytes to hex representation. </p>
  
  <p>What I've tried so far:</p>
  
  <pre><code>ifstream::pos_type size;
  char * memblock;
  
  ifstream file (toread, ios::in|ios::binary|ios::ate);
    if (file.is_open())
    {
      size = file.tellg();
      memblock = new char [size];
      file.seekg (0, ios::beg);
      file.read (memblock, size);
      file.close();
  
      cout &lt;&lt; "the complete file content is in memory" &lt;&lt; endl;
  
  std::string tohexed = ToHex(memblock, true);
  
  
      std::cout &lt;&lt; tohexed &lt;&lt; std::endl;
  
     }
  </code></pre>
  
  <p>Converting to hex:</p>
  
  <pre><code>string ToHex(const string&amp; s, bool upper_case)
  {
      ostringstream ret;
  
      for (string::size_type i = 0; i &lt; s.length(); ++i)
          ret &lt;&lt; std::hex &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; (upper_case ? std::uppercase : std::nouppercase) &lt;&lt; (int)s[i];
  
      return ret.str();
  }
  </code></pre>
  
  <p>Result: <code>53514C69746520666F726D61742033</code>.</p>
  
  <p>When I open the original file with a hex editor, this is what it shows:</p>
  
  <pre><code>53 51 4C 69 74 65 20 66 6F 72 6D 61 74 20 33 00
  04 00 01 01 00 40 20 20 00 00 05 A3 00 00 00 47
  00 00 00 2E 00 00 00 3B 00 00 00 04 00 00 00 01
  00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 A3
  00 2D E2 1E 0D 03 FC 00 06 01 80 00 03 6C 03 D3
  </code></pre>
  
  <p>Is there a way to get the same desired output using C++?</p>
  
  <p><strong>Working solution</strong> (by Rob): </p>
  
  <pre><code>...
  
  std::string tohexed = ToHex(std::string(memblock, size), true);
  
  ...
  string ToHex(const string&amp; s, bool upper_case)
  {
      ostringstream ret;
  
      for (string::size_type i = 0; i &lt; s.length(); ++i)
      {
          int z = s[i]&amp;0xff;
          ret &lt;&lt; std::hex &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; (upper_case ? std::uppercase : std::nouppercase) &lt;&lt; z;
      }
  
      return ret.str();
  }
  </code></pre>