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

前端 未结 7 726
说谎
说谎 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 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);
    }
    

提交回复
热议问题