Reputation: 1119
I have the enum;
enum testMe {
one,
two,
three;
long longValue() {
return 1<<ordinal();
}
}
for (testMe myLoop = testMe.values()) {
System.out.println(value.longValue() + ":" + myLoop);
}
Looping through the enum gives me exactly what I expect for the shift on the ordinal of the values in the enum. However, I need to qualify on an parameter I pass in a long;
Long myLong = 3;
for (testMe myLoop = testMe.values()) {
if ((myLong & value.longValue()) != 0) {
System.out.println(value.longValue() + ":" + myLoop);
}
}
In this case only the One and Two will be printed. However, this method will only work to 32 values in the enum. Does anyone have any ideas how I could use the BigInteger???
BigInteger longValue() {
BigInteger one = BigInteger.valueOf(1);
return one.shiftLeft(ordinal());
Thanks C
Upvotes: 0
Views: 276
Reputation: 31290
BigInteger b =BigInteger.ZERO;
b = b.setBit( ordinal() );
You may also use BigInteger.and(BigInteger x).
enum OneTwo {
one,
two,
three;
BigInteger biValue() {
BigInteger bi = BigInteger.ZERO;
return bi.setBit(ordinal());
}
BigInteger biValue( BigInteger filter ) {
BigInteger bi = BigInteger.ZERO;
return bi.setBit(ordinal()).and(filter);
}
}
And a test:
BigInteger three = BigInteger.valueOf(3L);
for (OneTwo ot: OneTwo.values()) {
System.out.println( ot.biValue() + ":" + ot);
System.out.println( ot.biValue(three) + ":" + ot);
}
No problem with printing.
Or compare to zero
if( BigInteger.ZERO.equals( bi.setBit(ordinal()).and(filter) ) ){
// no bits in filter are set
}
Upvotes: 2
Reputation: 109547
Use EnumSet.
EnumSet<TestMe> set = new EnumSet<>(TestMe.class);
An EnumSet has the bit properties you desire, though unfortunately does not exhibit them as long[]
or such. Otherwise use a BitSet
.
Upvotes: 2