简体   繁体   中英

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM