C++ Problem Stuffing 8 bits into a char
<p>This is weird. It is a trivial problem:</p>

<p>A std::string with bits with length multiple of 8, the first 8 is: "10011100".</p>

<pre><code>//Convert each 8 bits of encoded string to bytes
unsigned char c = 0;
for(size_t i = 0; i &lt; encoded.size(); i += 8)
{
    for(size_t k = 0; k &lt; 8; k++)
    {
        c &lt;&lt;= k;
        if(encoded.at(i + k) == '1') c += 1;

        //Debug for first 8 bits
        if(i == 0) cout &lt;&lt; "at k = " &lt;&lt; k &lt;&lt; ", c = " &lt;&lt; (int)c &lt;&lt; endl;
    }
    outFile.write(reinterpret_cast&lt;char*&gt;(&amp;c), sizeof(char));
}
</code></pre>

<p><hr /></p>

<p>Yields the output:</p>

<pre><code>at k = 0, c = 1
at k = 1, c = 2
at k = 2, c = 8
at k = 3, c = 65
at k = 4, c = 17
at k = 5, c = 33
at k = 6, c = 64
at k = 7, c = 0
</code></pre>

<p>Which doesn't make sense. Shifting 2 places left and getting 8 from 2 is impossible. The max value it can have should be 111b = 7d and in this case should be 100b = 4d.</p>

<p>Enlight me.</p>
