Decimal floating point number to binary: Difference between revisions

Added FreeBASIC
(Added Sidef)
(Added FreeBASIC)
Line 309:
Base 10 -42. Digits: 2</pre>
Note again that a decimal value in binary is almost always a recurring sequence and that the ''exact'' decimal value of the actual binary sequence in the computer (of finite length) is not the same as the original decimal value. 23·34375 happens to be an exact decimal representation of a binary value whose digit count is less than that available to a double-precision floating-point variable. But although 1011·1101 has few digits, in decimal it converts to a recurring sequence in binary just as does 0·1.
 
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
 
' Expresses (or rounds) the fractional part to the same number of places in binary as the decimal to be converted.
' This is accurate for the numbers used in this exercise but in general would not be.
Function decToBin(d As Double) As String
Dim neg As String = ""
If d < 0.0 Then
d = -d
neg = "-"
End If
Dim i As Integer = Fix(d)
Dim f As Double = Frac(d)
If f = 0 Then
Return neg + Bin(i)
End If
Dim le As Integer = Len(Str(d)) - Len(Str(i)) - 1
Return neg + Bin(i) + "." + Bin(Fix((2.0 ^ le) * f + 0.5), le)
End Function
 
Function binToDec(s As String) As Double
If s = "" Then Return 0.0
Dim neg As Integer = 1
If Left(s, 1) = "-" Then
s = Mid(s, 2)
neg = -1
End If
Dim index As Integer = Instr(s, ".")
If index = 0 Then
Return ValLng("&B" + s) * neg
Else
Dim a As Integer = ValLng("&B" + Left(s, index - 1))
Dim b As Integer = ValLng("&B" + Mid(s, index + 1))
Dim le As Integer = Len(Mid(s, index + 1))
Return (a + b / (2.0 ^ le)) * neg
End If
End Function
 
Print "23.34375 => "; decToBin(23.34375)
Print "1011.11101 => " ; binToDec("1011.11101")
Print "-23.34375 => " ; decToBin(-23.34375)
Print "-1011.11101 => " ; binToDec("-1011.11101")
Print "64 => "; decToBin(64)
Print "-100001 => " ; binToDec("-100001")
Print
Print "Press any key to quit"
Sleep</lang>
 
{{out}}
<pre>
23.34375 => 10111.01011
1011.11101 => 11.90625
-23.34375 => -10111.01011
-1011.11101 => -11.90625
64 => 1000000
-100001 => -33
</pre>
 
=={{header|Haskell}}==
9,482

edits