title: Endian-ness in a char array containing binary characters
body: <p>I'm building some code to read a RIFF wav file and I've bumped into something odd.</p>
  
  <p>The first 4 bytes of the file header are the word RIFF in <em>big-endian</em> ascii coding:</p>
  
  <pre><code>   0x5249 0x4646
  </code></pre>
  
  <p>I read this first element using:</p>
  
  <pre><code>char *fileID = new char[4];
  filestream.read(fileID,4);
  </code></pre>
  
  <p>When I write this to screen the results are as expected:</p>
  
  <pre><code>std::cout &lt;&lt; fileID &lt;&lt; std::endl;
  &gt;&gt;  RIFF
  </code></pre>
  
  <p>Now, the next 4 bytes give the size of the file, but crucially they're <em>little-endian</em>.</p>
  
  <p>So, I write a little function to flip the bytes, based on a union:</p>
  
  <pre><code>int flip4bytes(char* input){
  
     union flip {int flip_int; char flip_char[4];};
  
     flip.flip_char[0] = input[3];
     flip.flip_char[1] = input[2];
     flip.flip_char[2] = input[1];
     flip.flip_char[3] = input[0];
  
     return flip.flip_int;
  
   }
  </code></pre>
  
  <p>This looks good to me, except when I call it, the value returned is totally wrong. Interestingly, the following code (where the bytes are <em>not</em> reversed!) works correctly:</p>
  
  <pre><code>int flip4bytes(char* input){
  
     union flip {int flip_int; char flip_char[4];};
  
     flip.flip_char[0] = input[0];
     flip.flip_char[1] = input[1];
     flip.flip_char[2] = input[2];
     flip.flip_char[3] = input[3];
  
     return flip.flip_int;
  
   }
  </code></pre>
  
  <p>This has thoroughly confused me. Is the union somehow reversing the bytes for me?! If not, how are the bytes being converted to int correctly without being reversed?</p>
  
  <p>I think there's some facet of endian-ness here that I'm ignorant to..</p>