交换字节数组中的字节

时间:2014-06-25 16:30:06

标签: c# .net byte

有没有人知道是否有.NET函数来交换字节数组中的字节?

例如,假设我有一个包含以下值的字节数组:

byte[] arr = new byte[4];

[3] 192
[2] 168
[1] 1
[0] 4

我想交换它们以便数组变为:

[3] 168
[2] 192
[1] 4
[0] 1
[p]的Val与[2]的val和[1]的val交换,val为[0]

2 个答案:

答案 0 :(得分:4)

这种扩展方法怎么样:

public static class ExtensionMethods
{
    /// <summary>Swaps two bytes in a byte array</summary>
    /// <param name="buf">The array in which elements are to be swapped</param>
    /// <param name="i">The index of the first element to be swapped</param>
    /// <param name="j">The index of the second element to be swapped</param>
    public static void SwapBytes(this byte[] buf, int i, int j)
    {
        byte temp = buf[i];
        buf[i] = buf[j];
        buf[j] = temp;
    }
}

用法:

class Program
{
    void ExampleUsage()
    {
        var buf = new byte[] {4, 1, 168, 192};
        buf.SwapBytes(0, 1);
        buf.SwapBytes(2, 3);
    }
}

答案 1 :(得分:1)

我听起来你想在整个数组中就地交换字节对。你可以这样做,从左到右处理数组:

public static void SwapPairsL2R( this byte[] a )
{
  for ( int i = 0 ; i < a.Length ; i+=2 )
  {
    int t  = a[i]   ;
    a[i]   = a[i+1] ;
    a[i+1] = a[i]   ;
    a[i]   = t      ;
   }
   return ;
}

左右交换没有太大区别。