如何将二进制字符串转换为float或double?

时间:2011-11-25 17:57:30

标签: c# binary floating-point double

在这个问题中,比尔蜥蜴问how to display the binary representation of a float or double

我想知道的是,给定一个适当长度的二进制字符串,我怎样才能执行反向操作(在C#中)?换句话说,如何将二进制字符串转换为float或double?

作为旁注,是否有任何位字符串不会产生有效的浮点数或双倍?


编辑:二进制字符串我的意思是一个0和1的字符串。

所以,我的输入将是这样的字符串:

01010101010101010101010101010101

我的输出应该是一个浮点数。 (或者,如果字符串中有64位,则为double。)

4 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

string bstr = "01010101010101010101010101010101";
long v = 0;
for (int i = bstr.Length - 1; i >= 0; i--) v = (v << 1) + (bstr[i] - '0');
double d = BitConverter.ToDouble(BitConverter.GetBytes(v), 0);
// d = 1.41466386031414E-314

答案 2 :(得分:1)

答案 3 :(得分:0)

这是一个不使用BitConverter且不受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;
}

此版本支持二进制字符串,表示Double.MinValueDouble.MaxValue之间的值,或1023个有效二进制数字。它溢出到Double.PositiveInfinityDouble.NegativeInfinity

@LukeH的答案仅支持表示Int64.MinValueInt64.MaxValue之间的值的二进制字符串,或63个有效二进制数字。

为什么你需要一个长度超过63位的二进制字符串供讨论。

如果您不想允许前导符号字符,则可以使用仅返回正值的更简单版本。

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;
}
相关问题