Skip to main content
 首页 » 编程设计

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

2024年02月06日12linjiqin

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

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; 
    } 
}