【发布时间】:2024-01-20 07:20:01
【问题描述】:
我有一个字节数组,它以小字节序从函数GetData() 接收枚举,我想将该数组转换为枚举集合。
如何将 LE 中的字节复制并转换为 C# 中的枚举值?我有 C++ 背景,对这门语言不太熟悉。
这是一个示例代码sn-p:
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'
}
}
【问题讨论】:
-
为什么不使用
Dictionary?您可以将 KeyValuePairs 存储在一起。 docs.microsoft.com/en-us/dotnet/api/… -
在一个循环中,
(BarID)BitConverter.ToInt32(foo, [pos]);,其中[pos] = 0, 4, ... -
@Jimi 如果我在 32 位系统上,这会以某种方式改变吗?枚举的大小会不同吗?
-
不,大小一样。但是,看看 Marc Gravell 写了什么。
-
BitConverter.IsLittleEndian
标签: c# casting endianness