Reconstituting numbers in C/C++
<p>I have a stream of bytes that is being read in from a socket (little endian).
Can someone tell me why only the last one of the methods below gives the correct answer?
I suspect it's to do with the carry bit but not sure.  I've always found that when
printing binary data in hex form. </p>

<p>e.g. </p>

<pre><code>printf("%02X", data);
</code></pre>

<p>it sometimes prints out funny values with 0xff in front.  The way to fix it seems to
be doing this.  This still occasionally happens when data is a char data type too:</p>

<pre><code>printf("%02X", data &amp; 0xff);
</code></pre>

<p>Heres a simplified example from what I was seeing with my byte stream.
Where bytes would be the stream of bytes I've read from the socket.</p>

<pre><code>int main(int argc, char* argv[])
{
    union {
        unsigned int num;
        char bytes[4];
    } x;

    x.num = 500;
    printf("x.num=%u\n", x.num);

    unsigned int method1 = x.bytes[0] | (x.bytes[1] &lt;&lt; 8) | (x.bytes[2] &lt;&lt; 16) | (x.bytes[3] &lt;&lt; 24);
    printf("method1 = %u\n", method1);

    unsigned int method2 = x.bytes[0] + (x.bytes[1] &lt;&lt; 8) + (x.bytes[2] &lt;&lt; 16) + (x.bytes[3] &lt;&lt; 24);
    printf("method2 = %u\n", method2);

    unsigned int method3 = (x.bytes[0] &amp; 0xff | (x.bytes[1] &amp; 0xff) &lt;&lt; 8 
                            | (x.bytes[2] &amp; 0xff) &lt;&lt; 16 | (x.bytes[3] &amp; 0xff) &lt;&lt; 24);
    printf("method3 = %u\n", method3);

    return 0;
}
</code></pre>

<p>Which outputs:</p>

<pre><code>x.num=500
method1 = 4294967284
method2 = 244
method3 = 500
</code></pre>

<p>Only the last extract is actually correct.
Is my method of building up the numbers the most optimal?  I also tried a <code>memcpy</code> to a variable but again that wasn't reliable.</p>
