更快的方式交换字节序在C#与32位字 [英] Faster way to swap endianness in C# with 32 bit words
本文介绍了更快的方式交换字节序在C#与32位字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在<一个href=\"http://stackoverflow.com/questions/1610868/faster-way-to-swap-endianness-in-c-sharp-with-16bit-words\">this问题,下面code:
公共静态无效交换(字节[]数据)
{
的for(int i = 0; I&LT; data.Length;我+ = 2)
{
字节B =数据[I]
数据[I] =数据[I + 1];
数据第[i + 1] = B;
}
}
在不安全code被重写,以提高其性能:
公共静态不安全无效SwapX2(字节[]来源)
{
固定(BYTE *的PSource =放大器;来源[0])
{
BYTE * BP =的PSource;
BYTE * bp_stop = BP + Source.Length; 而(BP&LT; bp_stop)
{
*(* UINT16)BP =(UINT16)(* BP的LT;&LT; 8 | *(BP + 1));
碱基+ = 2;
}
}
}
假设人愿意做同样的事情与32位字:
公共静态无效SwapX4(字节[]数据)
{
字节温度;
的for(int i = 0; I&LT; data.Length; I + = 4)
{
TEMP =数据[I]
数据[I] =数据第[i + 3];
数据[1 + 3] =温度;
TEMP =数据[I + 1];
数据第[i + 1] =数据第[i + 2];
数据[1 + 2] =温度;
}
}
如何将本以类似的方式被重写
解决方案
公共静态不安全无效SwapX4(字节[]来源)
{
固定(BYTE *的PSource =放大器;来源[0])
{
BYTE * BP =的PSource;
BYTE * bp_stop = BP + Source.Length; 而(BP&LT; bp_stop)
{
*(* UInt32的)BP =(UInt32的)(
(* BP的LT;&LT; 24)|
(*(BP + 1) - ;&下; 16)|
(*(BP + 2)所述;&下; 8)|
(*(BP + 3)));
BP + = 4;
}
}
}
请注意,这两个功能(我SwapX4和你SwapX2)将只一小端主机上交换任何东西;当大端主机上运行,它们是一种昂贵的无操作。
In this question, the following code:
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;
}
}
was rewritten in unsafe code to improve its performance:
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;
}
}
}
Assuming that one wanted to do the same thing with 32 bit words:
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;
}
}
how would this be rewritten in a similar fashion?
解决方案
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;
}
}
}
Note that both of these functions (my SwapX4 and your SwapX2) will only swap anything on a little-endian host; when run on a big-endian host, they are an expensive no-op.
这篇关于更快的方式交换字节序在C#与32位字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文