[英]How do I convert byte array to UInt32 array?
讓我們說在 C++ 中我得到了這樣的代碼..
void * target
uint32 * decPacket = (uint32 *)target;
所以在 C# 中它會像..
byte[] target;
UInt32[] decPacket = (UInt32[])target;
無法將類型 byte[] 轉換為 uint[]
我如何將 C++ 的這種內存對齊方式轉換為數組到 C#?
好吧,接近於使用Buffer.BlockCopy
:
uint[] decoded = new uint[target.Length / 4];
Buffer.BlockCopy(target, 0, decoded, 0, target.Length);
請注意, BlockCopy
的最后一個參數始終是要復制的字節數,無論您要復制的類型如何。
你不能在 C# 中將byte
數組視為uint
數組(至少不是在安全代碼中;我不知道在不安全代碼中) - 但Buffer.BlockCopy
會將byte
數組的內容放入uint
數組中...讓結果取決於系統的字節序。 就我個人而言,我不喜歡這種方法 - 當您移動到具有不同內存布局的系統時,它會使代碼很容易出錯。 我更喜歡在我的協議中明確。 希望它會在這種情況下幫助你。
如果您願意轉向陰暗面,您可以擁有蛋糕(避免分配)並吃掉它(避免迭代)。
查看我對相關問題的回答,其中演示了如何將 float[] 轉換為 byte[],反之亦然:將 float[] 轉換為 byte[] 的最快方法是什么?
正如 Jon 提到的,Buffer.BlockCopy 可以很好地復制它。
但是,如果這是一個互操作場景,並且您想直接作為uint[]
訪問字節數組,那么您可以做的最接近 C++ 的方法是使用不安全代碼:
byte[] target;
CallInteropMethod(ref target);
fixed(byte* t = target)
{
uint* decPacket = (uint*)t;
// You can use decPacket here the same way you do in C++
}
我個人更喜歡制作副本,但如果您需要避免實際復制數據,這確實允許您工作(在不安全的環境中)。
我使用了 BitConverter.ToUInt32() - https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter.touint32?view=netcore-3.1
byte[] source = new byte[n];
UInt32 destination;
destination = BitConverter.ToUInt32(source, 0);
這對我來說似乎很好。
您可以使用Buffer.BlockCopy
。 而不是Array.Copy
, BlockCopy
做一個字節級拷貝而不檢查陣列類型是完全兼容。
像這樣:
uint[] array = new uint[bytes.Length/4];
Buffer.BlockCopy(bytes, 0, array, 0, bytes.Length);
循環遍歷所有數組項並對每個項調用 Convert.ToUint32()。這里:
Uint32[] res = new Uint32[target.Length];
for(int i = 0;i <= target.Length;i++)
{
res[i] = Convert.ToUint32(target[i]);
}
這是來自 MSDN 的官方鏈接。 http://msdn.microsoft.com/en-us/library/469cwstk.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.