How do I convert byte array to UInt32 array?

这一生的挚爱 提交于 2019-12-10 04:23:07

问题


Lets say In C++ I got code like this..

void * target
uint32 * decPacket = (uint32 *)target;

So in C# it would be like..

byte[] target;
UInt32[] decPacket = (UInt32[])target;

Cannot convert type byte[] to uint[]

How do I convert this memory aligning thing C++ does to arrays to C#?


回答1:


Well, something close would be to use Buffer.BlockCopy:

uint[] decoded = new uint[target.Length / 4];
Buffer.BlockCopy(target, 0, decoded, 0, target.Length);

Note that the final argument to BlockCopy is always the number of bytes to copy, regardless of the types you're copying.

You can't just treat a byte array as a uint array in C# (at least not in safe code; I don't know about in unsafe code) - but Buffer.BlockCopy will splat the contents of the byte array into the uint array... leaving the results to be determined based on the endianness of the system. Personally I'm not a fan of this approach - it leaves the code rather prone to errors when you move to a system with a different memory layout. I prefer to be explicit in my protocol. Hopefully it'll help you in this case though.




回答2:


You can have the cake (avoid allocations) and eat it too (avoid iterations), if you're willing to move to the dark side.

Check out my answer to a related question, in which I demonstrate how to convert float[] to byte[] and vice versa: What is the fastest way to convert a float[] to a byte[]?




回答3:


As Jon mentioned, Buffer.BlockCopy will work well for copying this.

However, if this is an interop scenario, and you want to access the byte array directly as uint[], the closest you can do is to the C++ approach would be to use unsafe code:

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

I personally prefer making the copy, but if you need to avoid actually copying the data, this does allow you to work (in an unsafe context).




回答4:


You can use Buffer.BlockCopy. Rather than Array.Copy, BlockCopy does a byte-level copy without checking the array types are fully compatible.

Like so:

uint[] array = new uint[bytes.Length/4];
Buffer.BlockCopy(bytes, 0, array, 0, bytes.Length);



回答5:


Loop over all array items and call Convert.ToUint32() on each of them.Here:

 Uint32[] res = new Uint32[target.Length];
 for(int i = 0;i <= target.Length;i++) 
 {
     res[i] = Convert.ToUint32(target[i]);
 }

Here is an official link from MSDN. http://msdn.microsoft.com/en-us/library/469cwstk.aspx



来源:https://stackoverflow.com/questions/7288897/how-do-i-convert-byte-array-to-uint32-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!