I’m getting a byte[] from an external input, where each byte stores two 4-bit values. My task is to read the 4-bit value of index idx 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…).
So the bytes and values look like (each [] is one byte):
[value0|value1] [value2|value3] [value4|value5] [value6|value7]
And I must retrieve the value with index idx. Obviously:
- If i is even, the expression is:
array[idx/2] & 0xF0 - If i is odd, the expression is:
array[idx/2] & 0x0F
So the code is:
if (idx % 2 == 0) {
return array[idx/2] & 0xF0;
}
return array[idx/2] & 0x0F;
Is this correct, and optimal?
UPDATE for “quick” readers: it is not correct, please see the Answer.
Your idea should be correct, but I think you may want to change the code to use a bit shift:
Because if you have
01000011, you may want to get4,3instead of64,3.By the way, I personally think that with the
elseblock the code will be clearer. The compiled opcode won’t be any different.