Reading 4-bit chunks from byte array
<p>I'm getting a <code>byte[]</code> from an external input, where each byte stores <strong>two</strong> 4-bit values. My task is to read the 4-bit value of index <strong>idx</strong> from this tightly packed array. I've never written such code, so I wonder if my below solution is correct, and if yes, then whether there is more optimal way to do it. (Please spare me from "why don't you test it yourself" comments; tests are not able to prove the correctness of something, only the incorrectness...).</p>

<p>So the bytes and values look like (each [] is one <code>byte</code>):</p>

<pre><code>[value0|value1] [value2|value3] [value4|value5] [value6|value7]
</code></pre>

<p>And I must retrieve the value with index <code>idx</code>. Obviously:</p>

<ul>
<li>If i is even, the expression is: <code>array[idx/2] &amp; 0xF0</code></li>
<li>If i is odd, the expression is: <code>array[idx/2] &amp; 0x0F</code></li>
</ul>

<p>So the code is:</p>

<pre><code>if (idx % 2 == 0) {
   return array[idx/2] &amp; 0xF0;
}
return array[idx/2] &amp; 0x0F;
</code></pre>

<p>Is this correct, and optimal?</p>

<hr>

<p><strong>UPDATE</strong> for "quick" readers: it is not correct, please see the Answer.</p>
