Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse binary representation of int (only significant bits)

Tags:

c#

.net

I'm trying to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11 right?

Here's my code:

static void Main(string[] args)
{
    Console.WriteLine("Enter a Number");
    int numb = int.Parse(Console.ReadLine());
    int reverse = 0;
    while (numb > 0)
    {
        int rem = numb % 10;
        reverse = (reverse * 10) + rem;
        numb = numb / 10;

    }
    Console.WriteLine("Reverse number={0}", reverse);
    Console.ReadLine();
}

By this code I only get the numbers to reverse (13 -> 31)...

The input should contain a single line with an integer N, 1≤N≤1000000000 and I want my output in one line with one integer, the number I want to get by reversing the binary representation of N.

like image 445
Cleon Avatar asked Feb 09 '23 23:02

Cleon


1 Answers

Something like that

// 13 = 1101b
int value = 13;

// 11 = 1011b
int result = Convert.ToInt32(new String(
        Convert.ToString(value, 2)
        .Reverse()
        .ToArray()), 2);

Explanation:

  • Convert.ToString(value, 2) returns value in binary representation ("1101")
  • Reverse().ToArray() - reverse the string ('1','0','1','1') as sequence of characters and converts to array char[].
  • new String(...) constructs string "1011" from array of char
  • finally, Convert.ToInt32(..., 2) convert binary representation back to int
like image 147
Dmitry Bychenko Avatar answered Feb 15 '23 12:02

Dmitry Bychenko