convert a two Byte bit mask into a EnumSet

久未见 提交于 2020-01-31 16:52:28

问题


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


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



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




回答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.



来源:https://stackoverflow.com/questions/1499833/convert-a-two-byte-bit-mask-into-a-enumset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!