Reverse the bits of a byte – c#

This method reverse the bits of a byte:


        // Reverses bits in a byte
        public static byte Reverse(byte inByte)
        {
            byte result = 0x00;

            for (byte mask = 0x80; Convert.ToInt32(mask) > 0; mask >>= 1)
            {
                // shift right current result
                result = (byte) (result >> 1);

                // tempbyte = 1 if there is a 1 in the current position
                var tempbyte = (byte)(inByte & mask);
                if (tempbyte != 0x00)
                {
                    // Insert a 1 in the left
                    result = (byte) (result | 0x80);
                }
            }

            return (result);
        }

A possible improvement could be to use this method to initialize the application to creating a table with all bytes and its inverted value.
Paying a slower initialization and more memory consumption all the conversions at runtime would be much faster.

Advertisements