usrso
usrso

Reputation: 75

C# floating point to binary string and vice versa

I am converting a floating point value to binary string representation:

float resulta = 31.0 / 15.0;    //2.0666666
var rawbitsa = ToBinaryString(resulta); //returns 01000000000001000100010001000100

where ToBinaryString is coded as:

static string ToBinaryString(float value)
{

        int bitCount = sizeof(float) * 8; // never rely on your knowledge of the size
        // better not use string, to avoid ineffective string concatenation repeated in a loop
        char[] result = new char[bitCount]; 

        // now, most important thing: (int)value would be "semantic" cast of the same
        // mathematical value (with possible rounding), something we don't want; so:
        int intValue = System.BitConverter.ToInt32(BitConverter.GetBytes(value), 0);

        for (int bit = 0; bit < bitCount; ++bit)
        {
            int maskedValue = intValue & (1 << bit); // this is how shift and mask is done.
            if (maskedValue > 0)
                maskedValue = 1;
            // at this point, masked value is either int 0 or 1
            result[bitCount - bit - 1] = maskedValue.ToString()[0];
        }

        return new string(result); // string from character array
}

Now I want to convert this binary string to float value.

I tried the following but it returns value "2.8293250329111622E-315"

string bstra = "01000000000001000100010001000100";
long w = 0;
for (int i = bstra.Length - 1; i >= 0; i--) w = (w << 1) + (bstra[i] - '0');
double da = BitConverter.ToDouble(BitConverter.GetBytes(w), 0); //returns 2.8293250329111622E-315

I want the value "2.0666666" by passing in value "01000000000001000100010001000100"

Why am I getting a wrong value? Am I missing something?

Upvotes: 1

Views: 1585

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063774

You're making this a lot harder than it needs to be; the error seems to be mostly in the character parsing code, but you don't need to do all that.

You could try like this instead:

static string ToBinaryString(float value)
{
    const int bitCount = sizeof(float) * 8;
    int intValue = System.BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
    return Convert.ToString(intValue, 2).PadLeft(bitCount, '0');
}

static float FromBinaryString(string bstra)
{
    int intValue = Convert.ToInt32(bstra, 2);
    return BitConverter.ToSingle(BitConverter.GetBytes(intValue), 0);
}

Example:

float resulta = 31.0F / 15.0F; //2.0666666
var rawbitsa = ToBinaryString(resulta);
Console.WriteLine(rawbitsa); //01000000000001000100010001000100
var back = FromBinaryString(rawbitsa);
Console.WriteLine(back); //2.0666666

Note that the usage of GetBytes is kinda inefficient; if you're OK with unsafe code, you can remove all of that.

Also note that this code is CPU-specific - it depends on the endianness.

Upvotes: 4

Related Questions