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 Flag
s 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<bool> ToBinary(this int n)
{
for (int i = 0; i < 32; i++)
{
yield return (n & (1 << i)) != 0;
}
}
public static int ToInt(this IEnumerable<bool> b)
{
var n = 0;
var counter = 0;
foreach (var i in b.Trim().Take(32))
{
n = n | (i ? 1 : 0) << counter;
counter++
}
return n;
}
private static IEnumerable<bool> Trim(this IEnumerable<bool> 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();