User1291
User1291

Reputation: 8209

java - fast bitmasks larger than 64 bits

What is the most efficient data structure to handle (i.e. perform all bitwise operations on) bitmasks that are of a known size but larger than 64bits?

byte[]? BigInteger? Something else entirely?

Needs to be Java 7 compatible and should be fast (or at least as fast as can reasonably be expected, given their size) for things like

if(bitmask & 7 != 0){...}

and

bitmask1 |= bitmask2

and so on.

Upvotes: 1

Views: 1462

Answers (1)

Dinh
Dinh

Reputation: 779

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

Or you use a BitSet

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

Upvotes: 3

Related Questions