如何将字节数组转换为UInt32数组?

SSp*_*oke 6 c# arrays bytearray uint32

让我们说在C++中,我得到了这样的代码..

void * target
uint32 * decPacket = (uint32 *)target;
Run Code Online (Sandbox Code Playgroud)

所以在C#中就像...

byte[] target;
UInt32[] decPacket = (UInt32[])target;
Run Code Online (Sandbox Code Playgroud)

无法将byte []转换为uint []

我如何将C++对数组的内存对齐转换为C#?

Jon*_*eet 12

那么,接近的将是使用Buffer.BlockCopy:

uint[] decoded = new uint[target.Length / 4];
Buffer.BlockCopy(target, 0, decoded, 0, target.Length);
Run Code Online (Sandbox Code Playgroud)

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

您不能仅仅将byte数组视为uintC#中的数组(至少不是安全的代码;我不知道在不安全的代码中) - 但Buffer.BlockCopy会将byte数组的内容splat 到uint数组中...将结果保留到根据系统的字节顺序确定.就个人而言,我不是这种方法的粉丝 - 当你转移到具有不同内存布局的系统时,它会使代码容易出错.我更喜欢在我的协议中明确表达.希望它能在这种情况下帮助你.