Inverse binary representation of int (significant bits only)

I am trying to write a program to change numbers in binary format. For example, the binary representation of 13 is 1101, and the reversal gives 1011, which corresponds to the number 11 on the right?

Here is 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 get numbers only for the inverse (13 → 31) ...

The entry must contain a single line with an integer number of N, 1≤N≤1000000000 , and I want my conclusion was on one line with one integer number that I want to get by changing the binary representation of N .

+4
source share
3 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 the value in binary representation ( "1101")
  • Reverse().ToArray() - ('1','0','1','1') char[].
  • new String(...) "1011" char
  • , Convert.ToInt32(..., 2) int
+8

Convert.ToString Convert.ToInt32, 2 :

int numb = int.Parse(Console.ReadLine());
var reversedString = Convert.ToString(numb, 2).ReverseString();
var result = Convert.ToInt32(reversedString, 2);

...

public static string ReverseString(this string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}
0

A loss exercise will do this without using a conversion string.

I have very little bit trick experience, so there is probably a faster and better way to do this, but this seems to work:

 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 would call it like this:

var reversed = n.ToBinary().Reverse().ToInt();
0
source

Source: https://habr.com/ru/post/1608835/


All Articles