Make this C# SwapBytes code x64 compatible
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 = *(pt开发者_开发知识库r + 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:
unsafe protected void SwapBytes(byte* ptr, int nLength) {
byte* ptr2 = ptr + nLength - 1;
for(int i = 0; i < nLength / 2; i++) {
byte t = *ptr;
*ptr = *ptr2;
*ptr2 = t;
ptr++;
ptr2--;
}
}
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:
protected void SwapBytes(byte[] data) {
for(int i = 0, j = data.Length - 1; i < data.Length / 2; i++, j--) {
byte t = data[i];
data[i] = data[j];
data[j] = t;
}
}
精彩评论