3

How would I obtain a specific subset, say bits 5-10, of an int in Java?

Looking for a method where one can pass in specific bit positions. I'm not sure how I would create a mask that changes given the input, or even if that is how one should go about doing it.

I know this is how one would get the front say 10 bits of an int: (I think) int x = num >> 22;

John
  • 3,037
  • 8
  • 36
  • 68
  • 1
    Have you tried anything? If not google `bit masks` and try to create such a method yourself, people will be more likely to help if they see effort. – Hunter McMillen Apr 14 '13 at 17:13
  • [What is the best practice way to create a bitmask for a range of bits?](https://stackoverflow.com/q/21465833/995714), [Masking bits within a range given in parameter](https://stackoverflow.com/q/28035794/995714), [setting a range of bits to 1](https://stackoverflow.com/q/48436659/995714), [Fastest way to produce a mask with n ones starting at position i](https://stackoverflow.com/q/39321580/995714), [Creating a mask around a subsection \[i,j\] for a number](https://stackoverflow.com/q/56508967/995714), [set the m-bit to n-bit](https://stackoverflow.com/q/15917454/995714) – phuclv Jun 09 '19 at 02:09

2 Answers2

3

Say you have a number n, and want bits from i to j (i=5, j=10).

Note, that i=0 will give you the last bit

 int value = n & (((1 << (j-i)) - 1) << i );

will give you the result.

The left part is obvious: you have a value, and you will put a bitmask on it.

The value of the mask is ((1 << (j-i)) - 1) << i. It says:

  • Take a 1 bit (value: 0000000000000001)
  • Shift it left j-i times (value: 2^(10-5) = 2^5 = 32 = 0000000000100000)
  • Deduct 1 (value: 31 = 0000000000011111) - have you seen the lowest bits reversed?
  • Shift it left i times (value: 31*32=992 = 0000001111100000)

So, you have got the bitmask for bits 5 - 10 (more precisely, from 5 to 9, since 10th is not included).

gaborsch
  • 15,408
  • 6
  • 37
  • 48
1

To obtain value of bit 1 (bits are indexed from 0 to 31)

int val = bits & 0x002;

To obtain value of bit 16

int val = bits & (1<<16);

To obtain value of bit n

int val = bits & (1<<n);
Aubin
  • 14,617
  • 9
  • 61
  • 84