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:
array[idx/2] & 0xF0array[idx/2] & 0x0FSo 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:
if (idx % 2 == 0) {
return array[idx/2] >>> 4; // unsigned bit shift
}else{
return array[idx/2] & 0x0F;
}
Because if you have 01000011, you may want to get 4,3 instead of 64,3.
By the way, I personally think that with the else block the code will be clearer. The compiled opcode won't be any different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With