Convert.ToString() to binary format not working as expected

前端 未结 7 722
说谎
说谎 2021-01-17 10:33
int i = 20;
string output = Convert.ToString(i, 2); // Base2 formatting
i = -20;
output = Convert.ToString(i, 2);
Value   Expected                       


        
相关标签:
7条回答
  • 2021-01-17 10:47

    This is basically the same answer as everyone else has posted, just packaged in a method.

      /// <summary>
      /// Method to convert an integer to a string containing the number in binary. A negative 
      /// number will be formatted as a 32-character binary number in two's compliment.
      /// </summary>
      /// <param name="theNumber">self-explanatory</param>
      /// <param name="minimumDigits">if binary number contains fewer characters leading zeros are added</param>
      /// <returns>string as described above</returns>
      public static string IntegerToBinaryString(int theNumber, int minimumDigits)
      {
         return Convert.ToString(theNumber, 2).PadLeft(minimumDigits, '0');
      }
    
    0 讨论(0)
  • 2021-01-17 10:47

    This function does exactly what you want

    string ConvertToFuzzyFrogBinary(int input)
    {
        int prefix = (input).ToString("d8").Length-(Math.Abs((input))).ToString("d8").Length;
        string binary_num = "00000000000000000000000000000000".Substring(0,32-Convert.ToString(Math.Abs(input),2).Length)+Convert.ToString(Math.Abs(input),2);
        return "1".Substring(0,prefix)+binary_num.Substring(prefix,32-prefix);
    }
    
    0 讨论(0)
  • 2021-01-17 11:01
    int value = 31;
    string binary = Convert.ToString(value, 2);
    Console.WriteLine(binary.PadLeft(8, '0'));          // Outputs "00011111"
    
    0 讨论(0)
  • 2021-01-17 11:03

    for integer -20 is 11111111111111111111111111101100 System is using 2's Complement by default. 1's Complement is not ideal for calculation.

    (2's complement is invert of all bit plus one)

    in 2's Complement , which will make 20 + (-20) = 0, can compute math easily without concern positive or negative.

    for example, in signed char : 15 = 00001111, -18 = 2's Complement of (00010010) = 11101101 + 1 = 11101110

    00001111 +11101110 =11111101

    Since first bit is 1, we know it is a negative value. Let's do a reverse 2's Complement.

    11111101 - 1 = 11111100 => -(00000011) it gives -3 which 15 + (-18) = -3

    0 讨论(0)
  • 2021-01-17 11:04

    Negative numbers in .NET are represented in binary as Two's complement.

    From MSDN - Convert.ToString Method (Int32, Int32):

    If value is negative and toBase is 2, 8, or 16, the returned string uses two's complement representation

    0 讨论(0)
  • 2021-01-17 11:08

    If you would get rid of this "effect" - use Math.Abs() method to get number value without sign,

    string output = Convert.ToString(Math.Abs(i), 2); // Base2 
    
    0 讨论(0)
提交回复
热议问题