I'm putting together a small handful of extension methods, for converting numeric values to their binary equivalents.
But I'm running into a problem.
We may use a Convert.ToString()
overload to convert these types to binary:
Byte
Short
Integer
Long
For example:
Dim iInteger As Integer
Dim sBinary As String
iInteger = Integer.MaxValue
sBinary = Convert.ToString(iInteger, 2)
But there isn't an overload for Single
that accepts the base value. The single-argument overload returns scientific notation, not the binary value.
I've tried this code, adapted from this answer:
Public Function ToBinary(Value As Single) As String
Dim aBits As Integer()
Dim _
iLength,
iIndex As Integer
Select Case Value
Case < BitLengths.BYTE : iLength = 7
Case < BitLengths.WORD : iLength = 15
Case < BitLengths.DWORD : iLength = 31
Case < BitLengths.QWORD : iLength = 63
End Select
aBits = New Integer(iLength) {}
For iIndex = 0 To iLength
aBits(iLength - iIndex) = Value Mod 2
Value \= 2
Next
ToBinary = String.Empty
aBits.ForEach(Sub(Bit)
ToBinary &= Bit
End Sub)
End Function
Unfortunately, however, it returns inaccurate results:
Input: 1361294667
Result: Assert.AreEqual failed. Expected:<01010001001000111011010101001011>. Actual:<01010001001000111011010110000000>.
We can get the expected value from the Programmer View of the old Windows 7 calculator:
Given these, how may we reliably convert a Single
value to a binary string?
--EDIT--
I found this statement: "There is not an exact binary representation of 0.1 or 0.01." That pretty much says it all. I've decided to abandon this, as it's become clear that the effort is a fruitless pursuit.