Thomas Calc
Thomas Calc

Reputation: 3014

Reading 4-bit chunks from byte array

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:

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.

Upvotes: 4

Views: 2588

Answers (1)

Alvin Wong
Alvin Wong

Reputation: 12430

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.

Upvotes: 4

Related Questions