Leonardo Guzman
Leonardo Guzman

Reputation: 29

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. The result should be 1010.1. How to achieve that in C#?

Upvotes: 1

Views: 597

Answers (1)

Klaus Gütter
Klaus Gütter

Reputation: 11977

To convert the part before the decimal point, you can just use the built-in 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:

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

Upvotes: 1

Related Questions