rtheunissen
rtheunissen

Reputation: 7435

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

Would that mean that the 100th constant would have to be 1 << 100?

Upvotes: 3

Views: 2721

Answers (5)

wolfcastle
wolfcastle

Reputation: 5930

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

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533730

You can use a BitSet which has any number bits you want to set or clear. e.g.

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

Upvotes: 15

GriffeyDog
GriffeyDog

Reputation: 8386

Yes, if you intend to be able to bitwise OR any or all of those constants together, then you're going to need a bit representing each constant. Of course if you use an int you will only have 32 bits and a long will only give you 64 bits.

Upvotes: 0

Jack
Jack

Reputation: 133609

You can't do it directly because maximum size for a primitive number which can be used as a bitmask is actually 64 bit for a long value. What you can do is to split the bitmask into 2 or more ints or longs and then manage it by hand.

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;
}

Upvotes: 4

Lee Meador
Lee Meador

Reputation: 12985

You can only create a simple bitmask with the number of bits in the primitive type.

If you have a 32 bit (as in normal Java) int then 1 << 31 is the most you can shift the low bit.

To have larger constants you use an array of int elements and you figure out which array element to use by dividing by 32 (with 32 bit int) and shift with % 32 (modula) into the selected array element.

Upvotes: 4

Related Questions