在
this question,以下代码:
public static void Swap(byte[] data) { for (int i = 0; i < data.Length; i += 2) { byte b = data[i]; data[i] = data[i + 1]; data[i + 1] = b; } }
public static unsafe void SwapX2(Byte[] Source) { fixed (Byte* pSource = &Source[0]) { Byte* bp = pSource; Byte* bp_stop = bp + Source.Length; while (bp < bp_stop) { *(UInt16*)bp = (UInt16)(*bp << 8 | *(bp + 1)); bp += 2; } } }
假设一个人想用32位字做同样的事情:
public static void SwapX4(byte[] data) { byte temp; for (int i = 0; i < data.Length; i += 4) { temp = data[i]; data[i] = data[i + 3]; data[i + 3] = temp; temp = data[i + 1]; data[i + 1] = data[i + 2]; data[i + 2] = temp; } }
这将如何以类似的方式重写?
解决方法
public static unsafe void SwapX4(Byte[] Source) { fixed (Byte* pSource = &Source[0]) { Byte* bp = pSource; Byte* bp_stop = bp + Source.Length; while (bp < bp_stop) { *(UInt32*)bp = (UInt32)( (*bp << 24) | (*(bp + 1) << 16) | (*(bp + 2) << 8) | (*(bp + 3) )); bp += 4; } } }
请注意,这两个功能(我的SwapX4和SwapX2)只会交换一个小端主机上的任何东西;当在一个大端主机上运行时,它们是一种昂贵的操作.