Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 appropriate length, how could I perform the reverse operation (in C#)? In other words, how do I turn a binary string into a float or double?

As a side note, are there any bit strings which would not result in a valid float or double?


EDIT: By binary string I mean a string of 0s and 1s.

So, my input will be a string like this:

01010101010101010101010101010101

and my output should be a floating point number. (Or, if there were 64 bits in the string, a double.)

like image 439
Tom Wright Avatar asked Jan 18 '23 04:01

Tom Wright


2 Answers

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);
}
like image 176
LukeH Avatar answered Jan 20 '23 18:01

LukeH


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
like image 37
MagnatLU Avatar answered Jan 20 '23 17:01

MagnatLU