Is there a built-in function to reverse bit order

Viewed 31369

I've come up with several manual ways of doing this, but i keep wondering if there is something built-in .NET that does this.

Basically, i want to reverse the bit order in a byte, so that the least significant bit becomes the most significant bit.

For example: 1001 1101 = 9D would become 1011 1001 = B9

On of the ways to do this is to use bitwise operations if following this pseudo code:

for (i = 0; i<8; i++)
{
  Y>>1
  x= byte & 1
  byte >>1
  y = x|y;
}

I wonder if there is a function somewhere that will allow me to do all this in one single line. Also, do you know the term for such an operation, i'm sure there is one, but i can't remember it at the moment.

Thanks

8 Answers

You can loop through bits and and get them in reverse order:

public static byte Reverse(this byte b)
{
    int a = 0;
    for (int i = 0; i < 8; i++)
        if ((b & (1 << i)) != 0)
            a |= 1 << (7- i);
    return (byte)a;
}

10 years later. But I hope this helps someone. I did a reverse operation like this:

byte Reverse(byte value)
{
    byte reverse = 0;
    for (int bit = 0; bit < 8; bit++)
    {
        reverse <<= 1;
        reverse |= (byte)(value & 1);
        value >>= 1;
    }

    return reverse;
}
Related