Search code examples
c#type-conversiondoubleieee-754

How to transform double to IEEE754 format?


The function should return a string representation of a double type number in the IEEE754 format

public class GetIEEE754FormatAdapter : ITransformer<double, string>
    {     
        public string Transform(double obj)
        {
            return Encoding.UTF8.GetString(BitConverter.GetBytes(obj));
        }
    }

For example if obj is 122.625, the result should be a string 0100000001011110101010000000000000000000000000000000000000000000

My implementation is returning wrong result


Solution

  • This does the trick:

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(BinaryString(122.625));
            // 00000001011110101010000000000000000000000000000000000000000000
        }
    
        static string BinaryString(double value)
        {
            long bits = BitConverter.DoubleToInt64Bits(value);
            return Convert.ToString(bits, 2).Substring(1);
        }
    }