[英]Iterate through a byte array like it's Uint16[]
說我有一個像這樣的數組:
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)
不,C#無法提供一種安全地重新解釋一個對象的方法,就好像它是某種不同類型的對象一樣(您可以使用不安全的代碼來完成它,但是整個程序集最終會變成“不安全”)。
您可以使用BitConverter.ToUInt16()
,甚至將byte[]
包裝在MemoryStream
然后使用BinaryReader.ReadUInt16()
方法從byte []對象讀取。 但是從問題的措辭來看,您不想使用任何類似的方法。
您可以使用不安全的代碼來做到這一點:
fixed(byte* p = bytearray)
{
ushort* ptr=(ushort*)p;
for(int i = 0; i < bytearray.Length/2; i++)
{
//...
}
}
您不能像這樣強制轉換整個數組,至少不能在托管代碼中轉換。 您可以使用BitConverter.ToUInt16
進行轉換,如下所示:
UInt16[] uint16array = Enumerable
.Range(0, arr.Length/2)
.Select(i => BitConverter.ToUInt16(arr, 2*i))
.ToArray();
這個小助手方法應該可以幫助您
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.