Tutorial :convert a two Byte bit mask into a EnumSet



Question:

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>?


Solution:1

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


Solution:2

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.)


Solution:3

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »