如何转换字节数组UInt32的阵列? [英] How do I convert byte array to UInt32 array?

查看:243
本文介绍了如何转换字节数组UInt32的阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说在C ++中我得到了code这样的..

  void *的目标
UINT32 * decPacket =(UINT32 *)的目标;

因此​​,在C#中它会像..

 字节[]的目标;
UInt32的[] decPacket =(UInt32的[])的目标;


  

无法转换类型byte []为uint []


我如何把这种记忆的东西对准C ++确实给数组到C#?


解决方案

好了,一些接近是使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx\"><$c$c>Buffer.BlockCopy:

  UINT []德codeD =新的uint [target.Length / 4];
Buffer.BlockCopy(目标,0,德codeD,0,target.Length);

请注意,最后一个参数 BlockCopy 总是的字节数,复制,不管你是复制类型。

您不能只是把一个字节数组在C#(A UINT 阵列至少不会在安全code,我不知道在不安全code) - 但 Buffer.BlockCopy 将图示的字节的内容阵列到 UINT 阵列...而使结果根据系统的字节序来确定。就个人而言,我的的这种做法的粉丝 - 离开code,当你移动到一个系统不同的内存布局相当容易出错。我preFER是在我的协议明确。希望它会帮助你在这种情况下,虽然。

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#?

解决方案

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.

这篇关于如何转换字节数组UInt32的阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆