HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Reverse binary representation of an int (only significant bits)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
reversebitsbinaryrepresentationintonlysignificant

Problem

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 ToBinary(this int n)
{
    for (int i = 0; i  b)
{
    var n = 0;
    var counter = 0;

    foreach (var i in b.Trim().Take(32))
    {
        n = n | (i ? 1 : 0)  Trim(this IEnumerable 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();

Solution

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 >= 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

Code Snippets

static int Reverse(int input)
{
    uint x = unchecked((uint)input);
    uint y = 0;
    while (x != 0)
    {
        y <<= 1;    // Shift accumulated result left
        y |= x & 1; // Set the least significant bit if it is set in the input value
        x >>= 1;    // Shift input value right
    }
    return unchecked((int)y);
}
int t = 0x103;
Console.WriteLine(Convert.ToString(t, 2));
Console.WriteLine(Convert.ToString(Reverse(t), 2));
100000011
110000001

Context

StackExchange Code Review Q#105638, answer score: 8

Revisions (0)

No revisions yet.