views:

788

answers:

3

I am reading a binary file that has values stored in bit masks, both 1 Byte bit masks and 2 Byte bit masks. Each bit in the masks act as a switch that indicates where an Event has transpired.

Example of 1 Byte mask:

00000101

Indicates that Event one and Event 3 has transpired.

Example of Enum

public enum MyEnum 
{
    EventOne,
    EventTwo,
        ....;   
}

I have created a Enum MyEnum(as per Item 32 in Effective java, Second Edition) of the events. How can the binary bit masks be read into an EnumSet<MyEnum>?

A: 

One way would be to have two arrays, one indexed by the low byte and one by the high byte. Populate the arrays with corresponding sets.

DigitalRoss
A: 
List<MyEnum> list = new ArrayList<MyEnum>();
for (MyEnum value : MyEnum.values()) {
  if ((mask & (1 << value.ordinal())) != 0) {
    list.add(value);
  } 
}
return EnumSet.copyOf(list);

For the 2 byte mask, combine the 2 bytes into one int. eg:

int mask = (((int)hbyte) & 0xff) << 8 | (((int)lbyte) & 0xff);
Laurence Gonsalves
ILMTitan
ILMTitan: yes, you're right. I've fixed it now.
Laurence Gonsalves
I am pulling in the bytes as short's, so I was able to shorten the mask to int mask = (hbyte << 8) | (lbyte); It works, thanks.
WolfmanDragon
It'd be better to have a field in the enum indicating which bit the enum value corresponds to. Using ordinals is kind of brittle: If someone reorders the value declarations, the program breaks. Having a separate field shows your intent better.
gustafc
A: 

I find it handy to explicitly think of

 BIT0 = 1;
 BIT1 = 1<<1;
 BIT2 = 1<<2;

etc.

Then

  if (bitmask & BIT0)
    return EventOne;
  if (bitmask & BIT1)
    return EventTwo;

etc.

You can make an enum or whatever for BIT0, BIT1, etc. if you want (everyone will be able to see immediately at a glance what bit you're selecting, assuming that all documentation etc. is consistent about bit order :), or use the shift expressions directly (most programmers ought to know what it means but some may not).

(Though Laurence Gonsalves' answer is clever when each bit corresponds exactly to one of the enum members in order; be sure to document that clearly through.)

Reed Hedges