Home > OS >  What is the fastest way to reverse a byte array in c#?
What is the fastest way to reverse a byte array in c#?

Time:04-28

I'm working on a project that needs to be very fast so I am asking this question: What is the fastest way to reverse a byte array in c#? (including unsafe code)

CodePudding user response:

In-place? Probably something like this:

byte[] Reverse( byte[] b )
{
  for ( int i = 0 , int j = b.Length-1 ; i < j ;   i, --j )
  {
    arr[i] ^= arr[j] ;
    arr[j] ^= arr[i] ;
    arr[i] ^= arr[j] ;
  }
  return b;
}

Idempotent, where you allocate a new array to contain the reversed octets, probably something like this:

byte[] Reverse( byte[] b )
{
  byte[] r = new byte[b.Length];
  for ( int i = 0, int j = b.Length ; i < b.Length ; )
  {
    r[i  ] = b[--j];
  }
  return r;
}
  • Related