简体   繁体   English

如何将十进制(或浮点)转换为二进制? C#

[英]How to convert decimal (or float) to binary? C#

I have this given number, for example, 10.5 , and I want to convert it into its binary representation.我有这个给定的数字,例如10.5 ,我想把它转换成它的二进制表示。 The result should be 1010.1 .结果应该是1010.1 How to achieve that in C#?如何在 C# 中实现这一点?

To convert the part before the decimal point, you can just use the built-in Convert.ToString(integerPart, 2)要转换小数点前的部分,只需使用内置的Convert.ToString(integerPart, 2)

I don't believe there is such a built-in function for the fractional part, but you can do it like you learned in school for the decimal case:我不相信小数部分有这样一个内置的 function ,但你可以像在学校学到的小数部分一样:

// x must be < 1
string ConvertFractionalPart(double x, int maxDigits)
{
    var sb = new StringBuilder();
    while (x > 0 && sb.Length < maxDigits)
    {
        if (x >= 0.5)
        {
            sb.Append("1");
            x -= 0.5;
        }
        else
        {
            sb.Append("0");
        }
        x = 2*x;
    }
    return sb.ToString();
}

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

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