为什么 Marshal.Copy 改变字节的顺序?它接缝转换为 MSB(最高有效字节)。
示例代码:
string s = "abc 123";
byte[] data = StringToByteArray(s);
uint[] data2 = ByteArrayToUintArray(data);
//s[0] = a = 61
//data[0] = a = 61
//but data2[0] = " cba" = 0x20636261
public static byte[] StringToByteArray(string str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}
public static uint[] ByteArrayToUintArray(byte[] data)
{
int lenght = (data.Length + 3) / 4;
uint[] data2 = new uint[lenght];
GCHandle pinnedArray = GCHandle.Alloc(data2, GCHandleType.Pinned);
IntPtr ptr = pinnedArray.AddrOfPinnedObject();
//do your stuff
Marshal.Copy(data, 0, ptr, data.Length);
pinnedArray.Free();
return data2;
}