title: C++ Reading signed 32-bit integer value
body: <p>I have a multi-byte primitive type called s32 which I want to read from a byte array. </p>
  
  <p>The specifications are:</p>
  
  <ul>
  <li><p>It is a 32-bit signed integer value, stored in little-endian order.</p></li>
  <li><p>Negative integers are represented using 2's complement. </p></li>
  <li><p>It uses 1 to 5 bytes depending on the magnitude. Each byte contributes its low seven bits to the value. If the high (8th) bit is set, then the next byte is also a part of the value.</p></li>
  <li><p>Sign extension is applied: the seventh bit of the last byte of the encoding is propagated to fill out the 32 bits of the decoded value. </p></li>
  </ul>
  
  <p>In the case of U32 - unsigned 32-bit I come up with this (any comments welcomed!) but not sure how to modify it for S32. </p>
  
  <pre><code>char temp = 0; 
  u32 value = 0;
  size_t index = 0;
  
  for(int i = 0; i &lt; 5; i++)
  {
      if(i &lt; 4)
      {
          temp  = 0x7F &amp; buffer[index];
      }
      else
      {
          temp = 0x0F &amp; buffer[index];
      }
  
      value |= temp &lt;&lt; (7 * i);
  
      if(!(0x80 &amp; buffer[index])) break;
  
      ++index;
  }
  </code></pre>
  
  <p>Thanks everyone!</p>