title: How to write a 4 byte unsigned integer to binary
body: <p>Trying to figure out how to write an unsigned integer to a binary file. As I see it the integer shouldn't take more space then 4 bytes. I have two parts in the below code marked as <strong>Write v.1</strong> and <strong>Write v.2</strong>. The expected behavior would be for both of them to work, but only version 2 does, though it takes up more space then I figure it should.</p>
  <h2>Question</h2>
  <p><strike>How can I write an unsigned integer to a binary file in 4 bytes? If it's not possible, then please explain why not?</strike><br />
  How can I read and output the unsigned integer in version 1.</p>
  <h3>Code</h3>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  using namespace std;
  
  int main()
  {
    unsigned int x = 4294967295;
    ofstream outfile;
    streampos begin,end;
    ifstream myfile;
    streampos size;
    char * memblock;
  
    // Write v.1
    outfile.open(&quot;example.bin&quot;, ios::binary | ios::out | ios::trunc);
    outfile.write((char*)&amp;x, sizeof(unsigned int));
    outfile.close();
  
    // Output size
    myfile.open (&quot;example.bin&quot;, ios::binary | ios::in);
    begin = myfile.tellg();
    myfile.seekg (0, ios::end);
    end = myfile.tellg();
    cout &lt;&lt; &quot;size is: &quot; &lt;&lt; (end-begin) &lt;&lt; &quot; bytes.\n&quot;;
  
    // Output content
    size = myfile.tellg();
    memblock = new char[size];
    myfile.seekg (0, ios::beg);
    myfile.read (memblock, size);
    myfile.close();
  
    cout &lt;&lt; &quot;content: &quot; &lt;&lt; memblock &lt;&lt; &quot;\n&quot;;
  
    delete[] memblock;
  
    myfile.close();
  
    // Write v.2
    outfile.open(&quot;example.bin&quot;, ios::binary | ios::out | ios::trunc);
    outfile &lt;&lt; x;
    outfile.close();
  
    // Output size
    myfile.open (&quot;example.bin&quot;, ios::binary | ios::in);
    begin = myfile.tellg();
    myfile.seekg (0, ios::end);
    end = myfile.tellg();
    cout &lt;&lt; &quot;size is: &quot; &lt;&lt; (end-begin) &lt;&lt; &quot; bytes.\n&quot;;
  
    // Output content
    size = myfile.tellg();
    memblock = new char[size];
    myfile.seekg (0, ios::beg);
    myfile.read (memblock, size);
    myfile.close();
  
    cout &lt;&lt; &quot;content: &quot; &lt;&lt; memblock &lt;&lt; &quot;\n&quot;;
  
    delete[] memblock;
  }
  </code></pre>
  <h3>Output</h3>
  <pre><code>size is: 4 bytes.
  content: ����
  size is: 10 bytes.
  content: 4294967295
  </code></pre>