convert 4 bytes to 3 bytes in C++
<p>I have a requirement, where 3 bytes (24 bits) need to be populated in a binary protocol. The original value is stored in an int (32 bits). One way to achieve this would be as follows:-</p>

<p>Technique1:-</p>

<pre><code>long x = 24;
long y = htonl(x);
long z = y&gt;&gt;8;
memcpy(dest, z, 3);
</code></pre>

<p>Please let me know if above is the correct way to do it?</p>

<p>The other way, which i dont understand was implemented as below</p>

<p>Technique2:-</p>

<pre><code>typedef struct {
char data1;
char data2[3];
} some_data;

typedef union {
long original_data;
some_data data;
} combined_data;

long x = 24;

combined_data somedata;
somedata.original_data = htonl(x);

memcpy(dest, &amp;combined_data.data.data2, 3);
</code></pre>

<p>What i dont understand is, how did the 3 bytes end up in combined_data.data.data2 as opposed to  first byte should go into combined_data.data.data1 and next 2 bytes should go into
combined_data.data.data2?</p>

<p>This is x86_64 platform running 2.6.x linux and gcc.</p>

<p>PARTIALLY SOLVED:-
On x86_64 platform, memory is addressed from right to left. So a variable of type long with value 24, will have following memory representation</p>

<pre><code>|--Byte4--|--Byte3--|--Byte2--|--Byte1--|
   0          0         0        0x18
</code></pre>

<p>With htonl() performed on above long type, the memory becomes</p>

<pre><code>|--Byte4--|--Byte3--|--Byte2--|--Byte1--|
   0x18       0         0         0
</code></pre>

<p>In the struct some_data, the </p>

<pre><code>data1 = Byte1
data2[0] = Byte2
data2[1] = Byte3
data4[2] = Byte4
</code></pre>

<p>But my Question still holds, Why not simply right shift by 8 as shown in technique 1 ?</p>
