c# - 像 Uint16[] 一样遍历字节数组

标签 c# arrays

假设我有一个这样的数组:

byte[] arr = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}

我可以用像 Uint16 一样处理的元素以某种方式遍历它吗?我想让我的应用程序像 {0x1122, 0x3344, 0x5566, 0x7788} 一样对待它。

尝试使用 as 关键字,但编译器不允许:

byte[] bytearray = new byte[10];
UInt16[] uint16array = bytearray as UInt16[];

有什么办法吗? (无需创建另一个数组或每次迭代将两个字节转换为一个 uint16)

最佳答案

这个小辅助方法应该能帮到你

public static class helper
{
    public static UInt16[] ToUnit16(this byte[] arr)
    {
        if (arr == null)
            return null;

        var len = arr.Length;

        if ((len % 2) != 0)
            throw new ArgumentException("Must divide by 2");

        var count = len / 2;

        var result = new UInt16[count];
        do
        {
            result[--count] = (UInt16)((arr[--len]) | arr[--len] << 8);
        } while (count > 0);

        return result;
    }
}

关于c# - 像 Uint16[] 一样遍历字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26951960/

相关文章:

c# - C# 中的机器学习库

Javascript for 循环使用图像数组作为敌人

php - 在 PHP 中查找子数组匹配

javascript - 在数组中存储具有属性的对象 javascript

arrays - VBA:嵌入单元格中的字符串(例如 "35 miles") - 如何根据距离的大小格式化单元格?

C#:按降序对字典进行排序

c# - 大于或等于与 Fluent Validation 枚举的比较?

c# - 复制构造函数转到基础构造函数并覆盖复制的值

c# - C# 中的多键字典(另一种)?

包含二维数组类型的 C 结构定义