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

前端 未结 4 1953
悲哀的现实
悲哀的现实 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:13

    Here's a solution that doesn't use BitConverter and isn't limited by the range of Int64.

    static double BinaryStringToDouble(string s)
    {
      if(string.IsNullOrEmpty(s))
        throw new ArgumentNullException("s");
    
      double sign = 1;
      int index = 1;
      if(s[0] == '-')
        sign = -1;
      else if(s[0] != '+')
        index = 0;
    
      double d = 0;
      for(int i = index; i < s.Length; i++)
      {
        char c = s[i];
        d *= 2;
        if(c == '1')
          d += 1;
        else if(c != '0')
          throw new FormatException();
      }
    
      return sign * d;
    }
    

    This version supports binary strings that represent values between to Double.MinValue and Double.MaxValue, or 1023 significant binary digits. It overflows to Double.PositiveInfinity or Double.NegativeInfinity.

    @LukeH's answer only supports binary strings that represent values between to Int64.MinValue and Int64.MaxValue, or 63 significant binary digits.

    Why you'd have a need for a binary string that is more than 63 digits in length is up for discussion.

    If you don't want to allow a leading sign character, you can use this simpler version that only returns positive values.

    static double BinaryStringToDouble(string s)
    {
      if(string.IsNullOrEmpty(s))
        throw new ArgumentNullException("s");
    
      double d = 0;
      foreach(var c in s)
      {
        d *= 2;
        if(c == '1')
          d += 1;
        else if(c != '0')
          throw new FormatException();
      }
    
      return d;
    }
    

提交回复
热议问题