如何将二进制字符串转换为浮点数或双精度

本文关键字:浮点数 双精度 转换 字符串 二进制 | 更新日期: 2023-09-27 18:15:59

在这个问题中,Bill The Lizard问如何显示浮点数或双精度数的二进制表示。

我想知道的是,给定适当长度的二进制字符串,我如何执行反向操作(在c#中)?换句话说,如何将二进制字符串转换为浮点数或双精度数?

作为旁注,是否有任何位字符串不会导致有效的浮点数或双精度数?


编辑:我说的二进制字符串是指0和1的字符串。

所以,我的输入将是一个像这样的字符串:
01010101010101010101010101010101

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

如何将二进制字符串转换为浮点数或双精度

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

和Marc的回答一样,你又需要BitConverter了:

  • http://msdn.microsoft.com/en-us/library/system.bitconverter.todouble.aspx
  • http://msdn.microsoft.com/en-us/library/system.bitconverter.tosingle.aspx

这是一个不使用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之间值的二进制字符串。MinValue和Double。MaxValue,或1023位有效二进制数字。它溢出到Double。PositiveInfinity或Double.NegativeInfinity.

@LukeH的答案只支持表示到Int64之间的值的二进制字符串。MinValue和Int64。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;
}