Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading