将两个字节的位掩码转换为EnumSet [英] convert a two Byte bit mask into a EnumSet

查看:122
本文介绍了将两个字节的位掩码转换为EnumSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取一个二进制文件,该文件的值存储在位掩码中,即1字节位掩码和2字节位掩码.掩码中的每个位都用作指示事件发生位置的开关.

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.

1字节掩码的示例:

Example of 1 Byte mask:

00000101

表示事件一和事件 3发生了.

Indicates that Event one and Event 3 has transpired.

枚举

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

我已经创建了Enum MyEnum(根据有效的Java中的第32条,第二版).二进制位掩码如何读入EnumSet<MyEnum>?

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

推荐答案

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

对于2字节掩码,请将2字节合并为一个int.例如:

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

int mask = (((int)hbyte) & 0xff) << 8 | (((int)lbyte) & 0xff);

这篇关于将两个字节的位掩码转换为EnumSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆