-2

The problem is asking :

The user gives me integer n,

I convert it to binary in 16 bits,

inverse the binary,

then decode the inverse binary into a new integer.

example:

14769 is 0011100110110001 (the 2 zeros in the front are the problem for me)

inverse the binary:

1000110110011100

Decode:

36252

I wrote the code but when I convert to binary it only gives me 11100110110001 without 00 in front, so the whole inverse binary will change and the new integer will be different.

This is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace HelloWorld
{
  public class Program
  {
  public static void Main(string[] args)
  {
    long n, n1, p, i, r, sum, inv, inv1, newint;
    Console.WriteLine("give n:");
    n=long.Parse(Console.ReadLine());
    n1=n;
    p=1;
    sum=0;
    i=n;
    //for below is for the binary representation of n
    for(i=n;i!=0;i=i/2)
    {
      r=i%2;
      sum=sum+r*p;
      p=p*10;        
   }

   inv=0;
   //for below is to inverse the above binary representation 
   for(i=sum;i!=0;i=i/10) 
   {
     r=i%10;
     inv=10*inv+r;       
   }

   inv1=inv;
   newint=0;
   p=0;
   //for below is to decode the inverse binary to its decimal representation 
   for(i=inv;i!=0;i=i/10)
   {
     r=i%10;
     newint=newint+r*(long)Math.Pow(2,p);
     p=p+1;
   }
   Console.WriteLine("The number that you gave = {0} \nIts binary 
   representation = {1} \n\nThe inverse binary representation = {2} \nThe integer corresponding to the inverse binary number = {3}", n1, sum, inv1, newint); 
   } 
 }
 }

So how can i encode on 16 bits?

Edit:

1)We didn't learn built in functions

2)We didn't learn padding or Convert.Int...

3)We only know the for loop (+ while loop but better not use it)

4)We can't use strings either

  • 3
    What is stopping you from padding string to lenght of 16 ? – Selvin Jun 17 '22 at 11:41
  • Datatypes for numbers ignore zeros in front since they are basically nothing. Zeros in between will be saved. I may recommend either saving it as a char[] or as a string to make sure the input wont be formatted. – Cataklysim Jun 17 '22 at 11:43
  • [C# convert int to string with padding zeros?](https://stackoverflow.com/a/4325289) – 001 Jun 17 '22 at 11:44
  • If you want to have padding zeros in front, you must not use a number type ... – derpirscher Jun 17 '22 at 11:51
  • What is the actual goal? the example looks like it is from an example in a very old textbook for C. "binary representation" usually means representing some data as a sequence of bytes, and that is most easily done with `BitConverter` or `BinaryWriter`/`BinaryWriter`. Or see [this question](https://stackoverflow.com/questions/2954962/convert-integer-to-binary-in-c-sharp) if you want a binary string. – JonasH Jun 17 '22 at 11:52
  • Does this answer your question? [Is there a built-in function to reverse bit order](https://stackoverflow.com/questions/3587826/is-there-a-built-in-function-to-reverse-bit-order) – Charlieface Jun 17 '22 at 12:51
  • Charlieface- Unfortunately it doesn't :( – Elie Makdissi Jun 17 '22 at 13:01

2 Answers2

0

You can try using Convert to obtain binary representation and Aggregate (Linq) to get back decimal:

using System.Linq;
...

int value = 14769;
      
int result = Convert
  .ToString(value, 2) // Binary representation
  .PadLeft(16, '0')   // Ensure it is 16 characters long
  .Reverse()          // Reverse
  .Aggregate(0, (s, a) => s * 2 + a - '0'); // Back to decimal

Console.Write($"{value} => {result}");

Output:

14769 => 36252

Edit: Loop solution (if you are not allowed to use the classes above...)

int value = 14769;
int result = 0;

for (int i = 0, v = value; i < 16; ++i, v /= 2)
  result = result * 2 + v % 2;

Console.Write($"{value} => {result}");

Explanation (how for above works):

First of all how can we get all 16 bits of the number? We can use standard algorithm based on remainder:

14769 /  1 % 2 == 1,
14769 /  2 % 2 == 0,
14769 /  4 % 2 == 0,
14769 /  8 % 2 == 0,
14769 / 16 % 2 == 1,
...

these are the bits from right to left: 11100110110001. Typical code can be

int v = value; // we don't want to change value, let's work with its copy - v

for (int i = 0; i < 16; ++i) {
  // rightmost bit
  int bit = v % 2;

  // we divide v by to to get rid of the rightmost bit
  v = v / 2;
}

Note that we compute bits from right to left - in reverse order - the very order we are looking for! How can we build result from these bits?

result = bit0 + 2 * (bit1 + 2 * (bit2 + ...))))..)

So we can easily modify our loop into

int result = 0;

int v = value; // we don't want to change value, let's work with its copy - v

for (int i = 0; i < 16; ++i) {
  // rightmost bit
  int bit = v % 2;

  result = result * 2 + bit;

  // we divide v by to to get rid of the rightmost bit
  v = v / 2;
}

Finally, if we get rid of bit and make v declared within loop we can get my loop solution

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Prolly it is they homework/excercise ... so prolly using built-in function is not an option – Selvin Jun 17 '22 at 11:48
  • Selvin- exactly, i'll put this in edit – Elie Makdissi Jun 17 '22 at 11:50
  • Thank you i'll try the loop solution right now – Elie Makdissi Jun 17 '22 at 11:55
  • 1
    @Elie Makdissi: I see, I've edited the answer – Dmitry Bychenko Jun 17 '22 at 11:55
  • Dmitry Bychenko- Can you please only tell me how to do the binary representation of the given number by the user? Because i couldn't understand the for above. Is it possible to do it as 2 nested for? – Elie Makdissi Jun 17 '22 at 12:41
  • @Elie Makdissi: why should we use *nested* `for` here? Technically, you can put just *two* `for`: obtain all bits (1st `for`) and then aggregate them into `result` (2nd `for`). However, we don't need it: since bits appear from right to left - in reverse order - we can start aggregate them within the *same* `for` – Dmitry Bychenko Jun 17 '22 at 17:36
0

You could reverse the bits using some simple bitwise operators.

ushort num = 14769;
ushort result = 0;

// ushort is 16 bits, therefore exactly 16 iterations is required    
for (var i = 0; i < 16; i++, num >>= 1){
    // shift result bits left by 1 position
    result <<= 1;

    // add the i'th bit in the first position
    result |= (ushort)(num & 1);
}

Console.WriteLine(result); //36252

phuzi
  • 12,078
  • 3
  • 26
  • 50