[英]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.