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

2 thoughts on “Reverse the bits of a byte – c#

  1. MB says:

    Hello, mybe I missed something, but why do not use this:

    public static byte Reverse(byte inByte)
    {
    return (byte)~inByte;
    }

    …or even better do it in extension form:

    public static class ByteExtension
    {
    public static byte Reverse(this byte inByte)
    {
    return (byte)~inByte;
    }
    }

    then you will be able to use it in this way:

    byte b = 0xAA;
    byte inerted = b.Invert();

    Like

Your feedback is important...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s