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

前端 未结 7 723
说谎
说谎 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 11:08

    Here is a routine I wrote that does what the original questioner wanted. A mere 5 years too late!

    /// <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;
    }
    
    0 讨论(0)
提交回复
热议问题