简体   繁体   English

显示整数的16位

[英]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 这就是我现在所做的,我可以获得16位二进制形式的正整数
` `

        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 问题是我将如何获得16位二进制形式的整数的负值

like; 喜欢; when i input 5 , i can get : 0000000000000101 当我输入5时,我可以得到:0000000000000101

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

In C# int is a 32-bit type. 在C#中, int是32位类型。 You should use short (a 16-bit type) instead. 您应该改用short (16位类型)。 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. 对于最大为32767的正数, intshort的前16个(低)位相同,但对于负数则不同。

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 另外请记住,int包含32位

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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