说我有一个像这样的数组:
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/