简体   繁体   English

Convert.ToString() 为二进制格式未按预期工作

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

int i = 20;
string output = Convert.ToString(i, 2); // Base2 formatting
i = -20;
output = Convert.ToString(i, 2);
Value   Expected                            Actual
20      00000000000000000000000000010100    10100
-20     10000000000000000000000000010100    11111111111111111111111111101100

I can see that perhaps the binary output of 20 has been truncated but I do not understand the output for -20.我可以看到,也许 20 的二进制 output 已被截断,但我不明白 -20 的 output。 I based my expectations on base2 notation plus a belief that the signed element of an integer was expressed in the first left most digit.我的期望基于 base2 符号加上一个信念,即 integer 的有符号元素用最左边的第一个数字表示。 0 for positive and 1 for negative. 0 表示正,1 表示负。 Can someone explain the results, specifically that of -20?有人可以解释结果,特别是-20的结果吗?

Negative numbers in .NET are represented in binary as Two's complement . .NET 中的负数以二进制表示为二进制补码

From MSDN - Convert.ToString Method (Int32, Int32) :来自 MSDN - Convert.ToString 方法(Int32,Int32)

If value is negative and toBase is 2, 8, or 16, the returned string uses two's complement representation如果 value 为负且 toBase 为 2、8 或 16,则返回的字符串使用二进制补码表示

for integer -20 is 11111111111111111111111111101100 System is using 2's Complement by default.对于 integer -20 为 11111111111111111111111111101100 系统默认使用 2 的补码。 1's Complement is not ideal for calculation. 1 的补码不适合计算。

(2's complement is invert of all bit plus one) (2 的补码是所有位加一的反转)

in 2's Complement, which will make 20 + (-20) = 0, can compute math easily without concern positive or negative.在 2 的补码中,这将使 20 + (-20) = 0,可以轻松计算数学,而无需担心正负。

for example, in signed char: 15 = 00001111, -18 = 2's Complement of (00010010) = 11101101 + 1 = 11101110例如,在有符号字符中:15 = 00001111,-18 = (00010010) 的 2 补码 = 11101101 + 1 = 11101110

00001111 +11101110 =11111101 00001111 +11101110 =11111101

Since first bit is 1, we know it is a negative value.由于第一位是 1,我们知道它是一个负值。 Let's do a reverse 2's Complement.让我们做一个反向 2 的补码。

11111101 - 1 = 11111100 => -(00000011) it gives -3 which 15 + (-18) = -3 11111101 - 1 = 11111100 => -(00000011) 它给出 -3 其中 15 + (-18) = -3

int value = 31;
string binary = Convert.ToString(value, 2);
Console.WriteLine(binary.PadLeft(8, '0'));          // Outputs "00011111"

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

This function does exactly what you want这个 function 完全符合您的要求

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

Here is a routine I wrote that does what the original questioner wanted.这是我写的一个例程,它可以满足原始提问者的要求。 A mere 5 years too late!仅仅晚了5年!

/// <summary>Convert a number into a string of bits</summary>
/// <param name="value">Value to convert</param>
/// <param name="minBits">Minimum number of bits, usually a multiple of 4</param>
/// <exception cref="InvalidCastException">Value must be convertible to long</exception>
/// <exception cref="OverflowException">Value must be convertible to long</exception>
/// <returns></returns>
public static string ShowBits<T>(this T value, int minBits)
{
    long x = Convert.ToInt64(value);
    string retVal = Convert.ToString(x, 2);
    if (retVal.Length > minBits) retVal = Regex.Replace(retVal, @"^1+", "1");   // Replace leading 1s with a single 1 - can pad as needed below
    if (retVal.Length < minBits) retVal = new string(x < 0 ? '1' : '0', minBits - retVal.Length) + retVal;  // Pad on left with 0/1 as appropriate
    return retVal;
}

If you would get rid of this "effect" - use Math.Abs() method to get number value without sign,如果你想摆脱这种“影响” - 使用Math.Abs()方法来获取没有符号的数值,

string output = Convert.ToString(Math.Abs(i), 2); // Base2 

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

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