Reverse binary representation of an int (only significant bits) This based on this question in StackOverflow. The accepted answer uses Convert.ToString(int, base) to get the binary string, reverses it and converts it back to int. Nice trick!

I have very little experience with bit twidling (using Flags is about it :p ) so I decided to try and code the solution to this problema without using Convert.

I came up with the following solution. I'd like to know easier ways to do this as there are probably many much better than the one I found.

public static IEnumerable&lt;bool&gt; ToBinary(this int n)
{
    for (int i = 0; i &lt; 32; i++)
    {
        yield return (n &amp; (1 &lt;&lt; i)) != 0;
    }
}

public static int ToInt(this IEnumerable&lt;bool&gt; b)
{
    var n = 0;
    var counter = 0;

    foreach (var i in b.Trim().Take(32))
    {
        n = n | (i ? 1 : 0) &lt;&lt; counter;
        counter++
    }

    return n;
}

private static IEnumerable&lt;bool&gt; Trim(this IEnumerable&lt;bool&gt; list)
{
    bool trim = true;

    foreach (var i in list)
    {
        if (i)
        {
            trim = false;
        }

        if (!trim)
        {
            yield return i;
        }
    }
}


And now you'd use it like this:

var reversed = n.ToBinary().Reverse().ToInt();
You could use while loop instead of the for loop.
Thus you don't need to trim zero bits, because it will continue to loop only while there is at least one significant bit in a value.
Another advantage of this approach is that the result can be calculated using integer arithmetics only without using any kind of collections.

static int Reverse(int input)
{
    uint x = unchecked((uint)input);
    uint y = 0;
    while (x != 0)
    {
        y &lt;&lt;= 1;    // Shift accumulated result left
        y |= x &amp; 1; // Set the least significant bit if it is set in the input value
        x &gt;&gt;= 1;    // Shift input value right
    }
    return unchecked((int)y);
}


Usage example:

int t = 0x103;
Console.WriteLine(Convert.ToString(t, 2));
Console.WriteLine(Convert.ToString(Reverse(t), 2));


Result:

100000011
110000001