Reputation: 1443
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]
Upvotes: 1
Views: 5720
Reputation: 74197
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.
Upvotes: 0
Reputation: 137398
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);
}
}
Upvotes: 6