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.)
The same as in Marc's answer, you need
BitConverter
again:Here's a solution that doesn't use BitConverter and isn't limited by the range of Int64.
This version supports binary strings that represent values between to Double.MinValue and Double.MaxValue, or 1023 significant binary digits. It overflows to Double.PositiveInfinity or Double.NegativeInfinity.
@LukeH's answer only supports binary strings that represent values between to Int64.MinValue and Int64.MaxValue, or 63 significant binary digits.
Why you'd have a need for a binary string that is more than 63 digits in length is up for discussion.
If you don't want to allow a leading sign character, you can use this simpler version that only returns positive values.