title: C/C++ code to convert big endian to little endian
body: <p>I've seen several different examples of code that converts big endian to little endian and vice versa, but I've come across a piece of code someone wrote that <em>seems</em> to work, but I'm stumped as to why it does.  </p>
  
  <p>Basically, there's a char buffer that, at a certain position, contains a 4-byte int stored as big-endian.  The code would extract the integer and store it as native little endian.  Here's a brief example:</p>
  
  <pre><code>char test[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
  char *ptr = test;
  int32_t value = 0;
  value =  ((*ptr) &amp; 0xFF)       &lt;&lt; 24;
  value |= ((*(ptr + 1)) &amp; 0xFF) &lt;&lt; 16;
  value |= ((*(ptr + 2)) &amp; 0xFF) &lt;&lt; 8;
  value |= (*(ptr + 3)) &amp; 0xFF;
  printf("value: %d\n", value);
  </code></pre>
  
  <p>value: 66051</p>
  
  <p>The above code takes the first four bytes, stores it as little endian, and prints the result. Can anyone explain step by step how this works?  I'm confused why ((*ptr) &amp; 0xFF) &lt;&lt; X wouldn't just evaluate to 0 for any X >= 8.  </p>