[英]How do I turn a binary string into a float or double?
在這個問題中,Bill The Lizard詢問如何顯示float或double的二進制表示 。
我想知道的是,給定一個適當長度的二進制字符串,我怎樣才能執行反向操作(在C#中)? 換句話說,如何將二進制字符串轉換為float或double?
作為旁注,是否有任何位串不會導致有效的浮點數或雙倍?
編輯:二進制字符串我的意思是一個0和1的字符串。
所以,我的輸入將是這樣的字符串:
01010101010101010101010101010101
我的輸出應該是一個浮點數。 (或者,如果字符串中有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);
}
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
這是一個不使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.