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;
               order[7-i] = 0;

         double result = 0;
         for (int i = 0; i < 8; i++)
         return (short)result;

Anyone know a faster way?

7 Years
Discussion Span
Last Post by ddanbe

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();
b = Convert.ToByte(new string(chars), 2);


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

Edited by ddanbe: n/a


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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.