Reading 4-bit chunks from a byte array

I am getting byte[]

from external input where each byte stores two 4 bit values. My task is to read the 4-bit idx index value from this densely packed array. I have never written code like this, so I wonder if the solution below is correct, and if so, is there a better way to do it. (Please spare me the comments "why don't you check it yourself", tests cannot prove the correctness of something, only incorrectness ...).

So the bytes and values ​​look like (each [] is one byte

):

[value0|value1] [value2|value3] [value4|value5] [value6|value7]

      

And I have to get the value with the index idx

. Obviously:

  • If I am even, the expression: array[idx/2] & 0xF0

  • If I am odd, the expression: array[idx/2] & 0x0F

So the code:

if (idx % 2 == 0) {
   return array[idx/2] & 0xF0;
}
return array[idx/2] & 0x0F;

      

Is this correct and optimal?


UPDATE for "quick" readers: this is not correct, see answer.

+3


source to share


1 answer


Your idea should be correct, but I think you can change the code to use the shift bit:

if (idx % 2 == 0) {
   return array[idx/2] >>> 4; // unsigned bit shift
}else{
    return array[idx/2] & 0x0F;
}

      



Because if you have 01000011

, you can get 4,3

instead 64,3

.

By the way, I personally think that with a block, the else

code will be clearer. The compiled opcode will not be different.

+3


source







All Articles