How do I turn a binary string into a float or double?

前端 未结 4 1951
悲哀的现实
悲哀的现实 2021-01-19 14:21

In this question, Bill The Lizard asks how to display the binary representation of a float or double.

What I\'d like to know is, given a binary string of the appropr

4条回答
  •  粉色の甜心
    2021-01-19 15:11

    double d1 = 1234.5678;
    string ds = DoubleToBinaryString(d1);
    double d2 = BinaryStringToDouble(ds);
    
    float f1 = 654.321f;
    string fs = SingleToBinaryString(f1);
    float f2 = BinaryStringToSingle(fs);
    
    // ...
    
    public static string DoubleToBinaryString(double d)
    {
        return Convert.ToString(BitConverter.DoubleToInt64Bits(d), 2);
    }
    
    public static double BinaryStringToDouble(string s)
    {
        return BitConverter.Int64BitsToDouble(Convert.ToInt64(s, 2));
    }
    
    public static string SingleToBinaryString(float f)
    {
        byte[] b = BitConverter.GetBytes(f);
        int i = BitConverter.ToInt32(b, 0);
        return Convert.ToString(i, 2);
    }
    
    public static float BinaryStringToSingle(string s)
    {
        int i = Convert.ToInt32(s, 2);
        byte[] b = BitConverter.GetBytes(i);
        return BitConverter.ToSingle(b, 0);
    }
    

提交回复
热议问题