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

前端 未结 7 725
说谎
说谎 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.

      /// 
      /// 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.
      /// 
      /// self-explanatory
      /// if binary number contains fewer characters leading zeros are added
      /// string as described above
      public static string IntegerToBinaryString(int theNumber, int minimumDigits)
      {
         return Convert.ToString(theNumber, 2).PadLeft(minimumDigits, '0');
      }
    

提交回复
热议问题