我有一个字节数组,该字节数组从函数GetData()
以很小的字节序字节顺序清除了枚举,我想将该数组转换为枚举的集合。如何将LE顺序中的字节复制并转换为C#中的枚举值?我有C ++背景,对语言不太熟悉。这是一个示例代码片段:
public enum BarID
{
TAG0 = 0x0B01,
TAG1 = 0x0B02,
}
public class TestClass
{
List<BarID> ids;
internal TestClass()
{
ids = new List<BarID>();
byte[] foo = GetData(); // returns 01 0b 00 00 02 0b 00 00
// cast byte array so that ids contains the enums 'TAG0' and 'TAG1'
}
}
不清楚数组值是按两个还是四个分组,但是模式基本上是相同的:
public enum BarID
{
TAG0 = 0x0B01,
TAG1 = 0x0B02,
}
public class TestClass
{
List<BarID> ids;
internal TestClass()
{
ids = new List<BarID>();
byte[] foo = GetData(); // returns 01 0b 00 00 02 0b 00 00
// cast byte array so that ids contains the enums 'TAG0' and 'TAG1'
//create a hash-set with all the enum-valid values
var set = new HashSet<int>(
Enum.GetValues(typeof(BarID)).OfType<int>()
);
//scan the array by 2-bytes
for (int i = 0; i < foo.Length; i += 2)
{
int value = foo[i] + foo[i + 1] << 8;
if (set.Contains(value))
{
ids.Add((BarID)value);
}
}
}
}
该集合不是强制性的,但应防止将无效值强制转换为标签。例如,如果值是基于单词的,则00 00
值无效。