1

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
SNYLMZ
  • 25
  • 1
  • 9

2 Answers2

4

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);
Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
  • THANK YOU SOO MUCH , YOU SAVED MY LIFE :D :D – SNYLMZ Oct 11 '15 at 19:46
  • First 16 bits are not different, they are the same. -5 in 32bit is 11111111111111111111111111111011, lower 16 bits are equal. – Antonín Lejsek Oct 11 '15 at 20:07
  • @AntonínLejsek In a positional notation first digit is the least significant digit, so "first bits" and "lower bits" means the same. I edited my answer though to avoid any confusion. – Jakub Lortz Oct 11 '15 at 20:22
0

This is a correct behavior since it is stored in that way in a computer. That is the so called two's complement where the most significant bit (the most left) tells you that this is a negative number. Also keep in mind that int contains 32 bits

rekire
  • 47,260
  • 30
  • 167
  • 264