1

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]

4
  • I'm not aware of anything. Chances are you'll just need to write yourself a helper function that takes an array and two indexes to swap (as Jon shows below). Commented Jun 25, 2014 at 16:34
  • @VP. I feel that a comment essentially instructing the OP to continue reading this page is somewhat redundant. Commented Jun 25, 2014 at 16:39
  • When I had originally posted the comment, you had not yet posted the answer, so the comment just said 'go ahead and roll your own'. However, after I saw you post that immediately thereafter, I figured I should mention there now exists an example further down the page. Commented Jun 25, 2014 at 16:42
  • @VP. Understood. That happens to me all the time; I would have just deleted the comment. Commented Jun 25, 2014 at 16:44

2 Answers 2

6

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the example, I created a method similar to this one but making it an extension is a nice addition, thanks for the help, I thought maybe there was already one defined in .NET.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.