Is it possible to create a bitmask for ~ 100 constants?

Does this mean the 100th constant must be 1 <100?

+3


source to share


5 answers


You cannot do this directly, because the maximum size for a primitive number that can be used as a bit mask is actually 64 bits for the value long

. What you can do is split the bitmask into 2 or more int

or long

and then manipulate it manually.



int[] mask = new int[4];
final int MAX_SHIFT = 32;

void set(int b) {
  mask[b / MAX_SHIFT] |= 1 << (b % MAX_SHIFT);
}

boolean isSet(int b) {
  return (mask[b / MAX_SHIFT] & (1 << (b % MAX_SHIFT))) != 0;
}

      

+4


source


You can use a BitSet, which has whatever bits of the number you want to set or clear. eg.



BitSet bitSet = new BitSet(101);
bitSet.set(100);

      

+14


source


You can create a simple bit mask with the number of bits in the primitive type.

If you have a 32-bit (as in normal Java) int, then 1 <31, you can shift the bottom bit.

To have large constants, you use an array of int elements, and you determine which element of the array to use by dividing by 32 (with a 32-bit int) and swapping from% 32 (modula) to the selected element of the array.

+4


source


Effective Java Item # 32 suggests using EnumSets instead of bitfields . Internally it uses a bit vector, so it is efficient, however it becomes more readable as each bit has a descriptive name (enum constant).

+2


source


Yes, if you intend to be able to bitwise OR any or all of these constants together, then you need a bit to represent each constant. Of course, if you use int

, you will only have 32 bits and long

will only give you 64 bits.

0


source







All Articles