Search code examples
c#complement

display the 16 bits for the integer


i need your help , here is a part of my code but there is a problem that i cant solve . Plese help me; This is what i have done for now , i can get positive integer in 16 bits binary form
`

        Console.WriteLine("Enter an integer : ");

        string inputnumber = Console.ReadLine();

        int num = int.Parse(inputnumber);

        string value = Convert.ToString(num, 2).PadLeft(16, '0');

        Console.WriteLine("The bits are : {0}", value);
        Console.ReadKey();`

AND the issue is how will i get negative value of an integer in 16 bits binary form

like; when i input 5 , i can get : 0000000000000101

   and i need -5 -------------> 1111111111111011

Solution

  • In C# int is a 32-bit type. You should use short (a 16-bit type) instead. For positive numbers up to 32767 the first (lower) 16 bits of int and short are the same, but for negative numbers it's different.

    short num = short.Parse(inputnumber);