Here is a piece of code borrowed from the “Endogine” engine. It is supposed to swap the byte order of any byte array :
unsafe protected void SwapBytes(byte* ptr, int nLength)
{
for(long i = 0; i < nLength / 2; ++i) {
byte t = *(ptr + i);
*(ptr + i) = *(ptr + nLength - i - 1);
*(ptr + nLength - i - 1) = t;
}
}
It seems to fail when I target the x64 architecture, but I can’t figure why, since no pointer is cast to int32.
Any help ?
In what way does it seem to fail? It seems pretty straight forward. I would use two pointers to make it a bit faster:
However, the compiler is pretty good at optimising loops and array accesses. It’s likely that managed code to do the same performs pretty close to the unsafe code: