I need to bit reverse 8-bit integers.

eg 208 (11010000) becomes 11 (00001011)

This works but it's too slow:

private short MyReverse(short a)
      {
         int[] order = new int[8];

         for (int i = 0; i < 8; i++)
         {
            if ((a & Convert.ToInt32((Math.Pow(2, i)))) != 0)
            {
               order[7-i] = 1;
            }
            else
            {
               order[7-i] = 0;
            }
         }

         double result = 0;
         for (int i = 0; i < 8; i++)
         {
            result+=order[i]*Math.Pow(2,i);
         }
         return (short)result;
      }

Anyone know a faster way?

1) A short is not an 8-bit integer. short is Int16.
2) There could be a better method than this, but here's something you can do.

byte b = 208;
char[] chars = Convert.ToString(b, 2).ToCharArray();
Array.Reverse(chars);
b = Convert.ToByte(new string(chars), 2);

Console.WriteLine(b);
Console.Read();

Yes, true.

The 8 bit word that comes from my device represents an 8 bit integer. However, the device's SDK sends the result as a short. The user throws away all but the lowest 8 bits. (stupid I know)

It orders these bits from lsb to msb. For board layout reasons, I would prefer msb to lsb.

The method I provided works. Yours should work well also and is free from the explicit loop but, being another high level implementation, I wonder if there is an in-memory work-around that would directly access the Low byte of the short. Unsafe code is OK.

You could use the shift left operator << here!
Math.Power is a very "expensive" function to call.
Convert.ToInt32((Math.Pow(2, i)
should give the same as 1<< i

a = Convert.ToInt32((Math.Pow(2, i);
b = 1 << i; //multyply by 2 by shifting 1 bit to the left
// a and b should be equal

Edit: i goes from 0 to 7 of course

Yes. that's much more elegant than my hack.

Sadly, it turns out that my bottleneck is in the hardware-code that collects the initial short from the port.

Thanks for your ideas.

Perhaps you could also have a look at this snippet.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.