Question

Why Marshal.Copy changes the order of the bytes? It seams to convert to MSB (most significant byte).

Sample code:

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;
    }
Was it helpful?

Solution

Assumed your program runs on an Intel processor, the integer format is little-endian, which means the least significant byte comes first. So 0x20636261 is actually stored in memory as

 0x61 0x62 0x63 0x20

which means Marshal.Copy did not change the byte order, you just misunderstood the correct order for how to decode the integer value into a sequence of bytes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top