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

前端 未结 7 790
说谎
说谎 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!

    /// Convert a number into a string of bits
    /// Value to convert
    /// Minimum number of bits, usually a multiple of 4
    /// Value must be convertible to long
    /// Value must be convertible to long
    /// 
    public static string ShowBits(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;
    }
    

提交回复
热议问题