title: C++ convert string of bytes to ints from file
body: <p>I'm completely new to C++, so I guess this might be a very trivial question.  If this is a duplicate of an already answered question (I bet it is...), please point me to that answer!</p>
  
  <p>I have a file with the following cut from <code>hexdump myfile -n 4</code>:</p>
  
  <pre><code>00000000  02 00 04 00 ...    |....|
  00000004
  </code></pre>
  
  <p>My problem/confusion comes when trying to read these values and convert them to ints ( [0200]_hex --> [512]_dec and [0400]_hex --> [1024]_dec).</p>
  
  <p>A minimum working example based on <a href="https://stackoverflow.com/a/1070499">this answer</a>:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;string&gt;
  using namespace std;
  int main(void){
      char fn[] = "myfile";
      ifstream file;
      file.open(fn, ios::in | ios::binary);
  
      string fbuff = "  ";
      file.read((char *)&amp;fbuff[0], 2);
      cout &lt;&lt; "fbuff: " &lt;&lt; fbuff &lt;&lt; endl;
  
      // works
      string a = "0x0200";
      cout &lt;&lt; "a: " &lt;&lt; a  &lt;&lt; endl;
      cout &lt;&lt; "stoi(a): " &lt;&lt; stoi(a, nullptr, 16) &lt;&lt; endl;
  
      // doesn't work
      string b = "\x02\x00";
      cout &lt;&lt; "b: " &lt;&lt; b &lt;&lt; endl;
      cout &lt;&lt; "stoi(b): " &lt;&lt; stoi(b, nullptr, 16) &lt;&lt; endl;
  
      // doesn't work
      cout &lt;&lt; "stoi(fbuff): " &lt;&lt; stoi(fbuff, nullptr, 16) &lt;&lt; endl;
  
      file.close();
      return(0);
  }
  </code></pre>
  
  <p>What I cant get my head around is the difference between <code>a</code> and <code>b</code>; the former defined with <code>0x</code> (which works perfect) and the latter defined with <code>\x</code> and breaks stoi. My guess is that whats being read from the file is in the <code>\x</code>-format, based on the output when running the code within sublime-text3 (below), and every example I've seen only deals with for example <code>0x0200</code>-formatted inputs</p>
  
  <pre><code>// Output from sublime, which just runs g++ file.cpp &amp;&amp; ./file.cpp
  fbuff: &lt;0x02&gt; &lt;0x00&gt;
  a: 0x0200
  stoi(a): 512
  b: 
  terminate called after throwing an instance of 'std::invalid_argument'
    what():  stoi
  [Finished in 0.8s with exit code -6]
  </code></pre>
  
  <p>Is there a simple way to read two, or more, bytes, group them and convert into a proper short/int/long?</p>