简体   繁体   中英

Swap bytes within an byte array

Does anyone know if there's a .NET function to swap bytes within an Byte Array?

For example, lets say I have a byte array with the following values:

byte[] arr = new byte[4];

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

I want to swap them so that the array becomes:

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

Val of [3] was swapped with val of [2] and val of [1] with val of [0]

How about this extension method:

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;
    }
}

Usage:

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

I sounds like you want to swap byte pairs in-place across the entire array. You could do something like this, process the array from left to right:

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 ;
}

Swapping right-left wouldn't be much different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM