How to convert byte array to UInt32 array?

Let's say that in C ++ I got code like this.

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

So in C # it will be like.

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

Unable to convert byte type [] to uint []

How to convert this memory binding that C ++ does for arrays in C #?

+6
source share
5 answers

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 copies, regardless of the types you copy.

You can't just treat the byte array as a uint array in C # (at least not in safe code, I don't know about unsafe code), but Buffer.BlockCopy will map the contents of the byte array to the uint array ... leaving the results to determine based on the essence of the system. Personally, I am not a fan of this approach - it leaves the code quite error prone when switching to a system with a different memory mask. I prefer to be explicit in my protocol. Hope this helps you in this case.

+11
source

You can have a cake (avoid selection) and eat it (avoid iteration) if you want to go to the dark side.

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

+2
source

As John noted , Buffer.BlockCopy will work well to copy this.

However, if this is an interaction scenario and you want to access the byte array directly as uint[] , the closest you can do is use the C ++ approach 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 to make a copy, but if you need to avoid actually copying the data, this allows you to work (in an insecure context).

+1
source

You can use Buffer.BlockCopy . Instead of Array.Copy , BlockCopy , byte-level copying is performed without checking array types.

Same:

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

Flip all the elements of the array and call Convert.ToUint32 () for 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 the official link from MSDN. http://msdn.microsoft.com/en-us/library/469cwstk.aspx

-1
source

Source: https://habr.com/ru/post/896521/


All Articles