c# - 将字节数组转换为 C# 中的枚举集合

标签 c# casting endianness

我有一个字节数组,它从函数 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'      

  }
}

最佳答案

这里有趣的一步是以小端方式可靠读取字节(这里的“可靠”意味着“在任何CPU上工作,而不仅仅是恰好是小端本身的CPU” );幸运的是,BinaryPrimitives让这一点显而易见,给你一个 int来自Span<byte> ( byte[] 中的 GetData() 可隐式转换为 Span<byte> )。然后从int你可以直接转换到 BarID :

Span<byte> foo = GetData();
var result = new BarID[foo.Length / 4];
for (int i = 0; i < result.Length; i++)
{
    result[i] = (BarID)BinaryPrimitives.ReadInt32LittleEndian(foo.Slice(4 * i));
}

Slice这里的步骤只是偏移我们应该在跨度中开始阅读的位置。

关于c# - 将字节数组转换为 C# 中的枚举集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62320913/

相关文章:

c# - 为什么使用 Attach 更新 Entity Framework 6?

c# - 如何避免 RCW 清理上的竞争

java - "pre-casting"与每次类型转换的效率

mysql - 将 BIGINT UNSIGNED 转换为 INT

c - 具有 htonl 和 ntohl 功能的 pdp endian

linux - Endianness:用户空间中的le32_to_cpu

c# - 将参数与 Func<> 一起使用

c# - MySQL 访问拒绝 C# 应用程序但不访问工作台

ios - 标签栏 Controller : accessing a property of inside UIViewController

ios - 在 iOS 上使用 AudioQueue 录制小端 PCM