There is a field with a size of 3 bytes. It is necessary to calculate the values ​​from 0 bits to 9 bits, then 2 bytes from 10 to 18, and (3 bytes) from 19 to 22. Also, 23 bits are not used, and it is zero.

I can not figure out how to make a view mask

mask = 0x0(xx - с 0 по 9)000 

The only thing that remains for me is to simply make a shift ( level = (value & mask) >> 8 ).

  • And what, in JAVA there is no bitwise AND? - BuilderC
  • is present, the problem is that I am Krivorukov, I cannot concoct a mask, that is, I need to translate the bits into a number. :( - Bezyshodnyi
  • True, I don’t know anything about the mask, but, solving this problem, I would shift to the right by 1 in a loop and check the last bit & 1. - BuilderC

1 answer 1

Let's start with the fact that the mask you imagine is wrong, because bits are indexed from right to left. Those. The 0th bit is the rightmost bit, which means you need to shift the bits to the left.

For simplicity, I’ll give a naive version of getting a mask so that it becomes clearer how it happens in steps:

  public static int buildMask(int n) { int mask = 0; for (int i = 0; i < n; i++) { mask |= 1 << i; } return mask; } 

If you look closely at the resulting masks, you can see that the mask is always equal to the number with the n th bit turned on minus 1, that is:

 int mask = (1 << n) - 1; 

Think about what will happen if in this way you try to generate a mask for all 32 included bits.

This is more than enough to solve your problem.