Decimal floating point number to binary: Difference between revisions

m
No edit summary
Line 1,378:
Base 2/4/8/16/32 are guaranteed to terminate anyway, but for other bases we need some limit -
the 15 that I opted for is completely arbitrary.
 
===shorter===
Inspired by Kotlin/Go/Wren (no attempt to handle signs, nor will it handle no-dot properly)
<lang Phix>function dec2bin(atom d)
integer whole = trunc(d)
string res = sprintf("%b.",whole)
d -= whole
while d>0 do
d *= 2
integer bit = (d>=1)
res &= '0'+bit
d -= bit
end while
return res
end function
function bin2dec(string s)
integer dot = find('.',s)
if dot then s[dot..dot] = "" end if
atom res = to_number(s, inbase:=2)
if dot then res /= power(2,length(s)+1-dot) end if
return res
end function
constant f = 23.34375,
s = dec2bin(f),
g = bin2dec(s),
t = "1011.11101",
h = bin2dec(t),
u = dec2bin(h)
printf(1,"%.5f => %s => %.5f\n", {f, s, g})
printf(1,"%s => %.5f => %s\n", {t, h, u})</lang>
{{out}}
<pre>
23.34375 => 10111.01011 => 23.34375
1011.11101 => 11.90625 => 1011.11101
</pre>
 
=={{header|Python}}==
7,820

edits