繁体   English   中英

从 java 中的字节数组中获取枚举

[英]Get enums from byte array in java

我有一个字节数组,其中包含 LE 字节顺序的枚举值。 我将如何遍历 java 中的这样一个数组并将每 4 个字节转换为一个枚举并将其放入这些枚举的数组中? 我有 C++ 背景,所以我更熟悉指针算法。 谢谢!

public enum MyEnum{
    TAG1(0x0C00),
    TAG2(0x0C01),
    TAG3(0x0C02);

    private final int id;

    MyEnum(int id) {
        this.id = id;
    }

    public int getValue() {
        return id;
    }
}


byte[] data = getData(); //  returns  for example '01 0c 00 00 02 0c 00 00' which would I want to interpret as as {TAG2, TAG3}
// this returns a byte array with the enums in LE byte order,
// one after the other

MyEnum[] enums = new MyEnum[data.length / 4];
// now I would copy each enum from the byte array to the enum 
// array, but unsure how to do that in Java

尝试这个。

Map<Integer, MyEnum> all = Arrays.stream(MyEnum.values())
    .collect(Collectors.toMap(MyEnum::getValue, e -> e));
byte[] data = { 0, 0xC, 0, 0, 1, 0xC, 0, 0, 2, 0xC, 0, 0 };
IntBuffer ib = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
MyEnum[] enums = new MyEnum[data.length / 4];
for (int i = 0; i < ib.capacity(); ++i)
    enums[i] = all.get(ib.get());
System.out.println(Arrays.toString(enums));
// -> [TAG1, TAG2, TAG3]

这样的事情怎么样

byte[] data = getData();
// this returns a byte array with the enums in LE byte order,
// one after the other

MyEnum[] enums = new MyEnum[data.length / 4];
// now I would copy each enum from the byte array to the enum 
// array, but unsure how to do that in Java

for (int i = 0; i < enums.length; i++) {
   // read whole enum
   int enumOrdinal = getOrdinalAt(data, i)
   MyEnum currentEnum = MyEnum.values()[enumOrdinal]
   enums[i] = currentEnum
}



private int getOrdinalAt(byte[] data, int enumIndex) {
   return data[enumIndex] || data[enumIndex + 1] || data[enumIndex + 2] || data[enumIndex + 3]
}

但是,如果您的data实际上包含枚举 ID,例如 0x0c00、0x0c01 等,则需要使用以下内容扩展您的枚举:


public enum MyEnum{
    TAG1(0x0C00),
    TAG2(0x0C01),
    TAG3(0x0C02);

    private final int id;

    MyEnum(int id) {
        this.id = id;
    }

       private static Map<Integer, MyEnum> map = new HashMap<>();

        static {
            for(MyEnum enum : MyEnum.values()) {
                map.put(enum.id, enum);
            }
        }

        public static MyEnum valueOf(int enumId) {
            return map.get(enumId);
        }


    public int getValue() {
        return id;
    }
}

一旦您从data中读取了字节,您只需使用MyEnum.valueOf(readThing)并获取适当的枚举。

例如 0x0c00 的 TAG1,0xc01 的 TAG2 等等

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM