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#?
Asked
Active
Viewed 307 times
1
-
Why would a binary value have a decimal point in it? If you _really_ want to keep the ending decimal point, just do two conversions, once for the stuff to the left, and once for the right, see the link below. – gunr2171 May 11 '21 at 04:05
-
Does this answer your question? [Convert integer to binary in C#](https://stackoverflow.com/questions/2954962/convert-integer-to-binary-in-c-sharp) – gunr2171 May 11 '21 at 04:06
-
2I don't understand the downvotes. That's a perfectly reasonable question - "1010.1" *is* the representation of 10.5 in base 2: 1*2^3 + 1*2^0 + 1*2^-1 – Klaus Gütter May 11 '21 at 05:07
1 Answers
1
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();
}

Klaus Gütter
- 11,151
- 6
- 31
- 36