Decimal floating point number to binary: Difference between revisions

m (→‎version 1: added wording to the REXX section header.)
Line 1,002:
<pre>23.34375 => 10111.01011
1011.11101 => 11.90625</pre>
=={{header|Phix}}==
Handles bases 2..36. Does not handle any form of scientific notation.
<lang Phix>function dec_to(atom d, integer base)
-- convert d to a string in the specified base
-- eg dec_to(65535,16) => "FFFF"
bool neg = d<0
if neg then d = -d end if
string res = ""
integer whole = floor(d)
d -= floor(d)
while true do
integer ch = mod(whole,base)
ch += iff(ch>9?'A'-10:'0')
res = ch&res
whole = floor(whole/base)
if whole=0 then exit end if
end while
if d>0 then
res &= '.'
while d>0 do
d *= base
integer digit = floor(d)
d -= digit
digit += iff(digit>9?'A'-10:'0')
res &= digit
end while
end if
if neg then res = '-'&res end if
return res
end function
 
function to_dec(string s, integer base)
-- convert the string s (in the specified base)
-- back into a normal decimal/floating point.
-- eg to_dec("FFFF",16) => 65535
bool neg = (s[1]='-')
if neg then s = s[2..$] end if
integer dot = find('.',s)
if dot then s[dot..dot] = "" end if
atom res = 0
for i=1 to length(s) do
integer ch = upper(s[i])
ch -= iff(ch>='A'?'A'-10:'0')
res = res*base + ch
end for
if dot then res /= power(base,length(s)-dot+1) end if
if neg then res = -res end if
return res
end function
 
procedure test(atom f, integer base=2)
string s = dec_to(f,base)
printf(1,"%.8g => 0(%d):%s\n", {f, base, s})
f = to_dec(s,base)
printf(1,"0(%d):%s => %.8g\n", {base, s, f})
end procedure
test(23.34375)
test(-23.34375)
test(11.90625)
test(-11.90625)
test(13)
test(0.1)
test(-5)
test(-0.25)
test(0)
test(65535,16)
?to_dec("23.7",10)
?dec_to(23.7,10)</lang>
{{out}}
<pre>
23.34375 => 0(2):10111.01011
0(2):10111.01011 => 23.34375
-23.34375 => 0(2):-10111.01011
0(2):-10111.01011 => -23.34375
11.90625 => 0(2):1011.11101
0(2):1011.11101 => 11.90625
-11.90625 => 0(2):-1011.11101
0(2):-1011.11101 => -11.90625
13 => 0(2):1101
0(2):1101 => 13
0.1 => 0(2):0.0001100110011001100110011001100110011001100110011001101
0(2):0.0001100110011001100110011001100110011001100110011001101 => 0.1
-5 => 0(2):-101
0(2):-101 => -5
-0.25 => 0(2):-0.01
0(2):-0.01 => -0.25
0 => 0(2):0
0(2):0 => 0
65535 => 0(16):FFFF
0(16):FFFF => 65535
23.7
"23.699999999999999289457264239899814128875732421875"
</pre>
Aside: I was quite surprised to get 100% accuracy on these tests, but actually it is more of
a lucky coincidence in the way it is written, as the last test shows. The truth of the matter
is simply that you can extract a float to a binary text representation exactly, in a way that
you just cannot do for most other (ie non-power-2) bases.
 
=={{header|Python}}==
Python has float.hex() and float.fromhex() that can be used to form our own binary format.
7,815

edits