Tom*_*ght 3 c# floating-point binary double
在这个问题中,Bill The Lizard询问如何显示float或double的二进制表示.
我想知道的是,给定一个适当长度的二进制字符串,我怎样才能执行反向操作(在C#中)?换句话说,如何将二进制字符串转换为float或double?
作为旁注,是否有任何位串不会导致有效的浮点数或双倍?
编辑:二进制字符串我的意思是一个0和1的字符串.
所以,我的输入将是这样的字符串:
01010101010101010101010101010101
Run Code Online (Sandbox Code Playgroud)
我的输出应该是一个浮点数.(或者,如果字符串中有64位,则为double.)
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);
}
Run Code Online (Sandbox Code Playgroud)