Decimal floating point number to binary: Difference between revisions

m
syntax highlighting fixup automation
No edit summary
m (syntax highlighting fixup automation)
Line 13:
{{trans|Kotlin}}
 
<langsyntaxhighlight lang="11l">F decToBin(d)
V whole = Int(floor(d))
V binary = bin(whole)‘.’
Line 35:
print(d"\t => "decToBin(d))
V s = ‘1011.11101’
print(s"\t => "binToDec(s))</langsyntaxhighlight>
 
{{out}}
Line 45:
=={{header|bc}}==
 
<syntaxhighlight lang="bc">
<lang bc>
obase = 2
scale=100
Line 52:
 
 
</syntaxhighlight>
</lang>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.array, std.string, std.range, std.algorithm, std.typecons;
 
immutable string[string] hex2bin, bin2hex;
Line 116:
y2.bin2dec.writeln;
writefln("%.6f", "1011.11101p+0".bin2dec);
}</langsyntaxhighlight>
{{out}}
<pre>1.011101011p+100
Line 127:
{{works with|dc|1.3.95 (GNU bc 1.06.95)}}
Interactively:
<langsyntaxhighlight lang="bash">$ dc
2o
23.34375 p
Line 138:
11.90625
q
$</langsyntaxhighlight>
 
Directly on the command line:
<langsyntaxhighlight lang="bash">$ dc -e '2o 23.34375 p'
10111.01011000000000000
$ dc -e '2i 1011.11101 p'
Line 149:
$ echo '2i 1011.11101 p' | dc
11.90625
$</langsyntaxhighlight>
 
From the manpage: "To enter a negative number, begin the number with '_'. '-' cannot be used for this, as it is a binary operator for subtraction instead."
<langsyntaxhighlight lang="bash">$ dc -e '2o _23.34375 p'
-10111.01011000000000000
$ dc -e '2i _1011.11101 p'
-11.90625
$</langsyntaxhighlight>
 
=={{header|Delphi}}==
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program FloatToBinTest;
 
Line 247:
Readln;
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 255:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def dec2bin(dec, precision\\16) do
[int, df] = case String.trim(dec) |> String.split(".") do
Line 307:
dec2 = RC.bin2dec(bin)
:io.format "~10s => ~18s =>~12s~n", [dec, bin, dec2]
end)</langsyntaxhighlight>
 
{{out}}
Line 322:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: interpolate io kernel math.parser sequences ;
 
: bin>dec ( x -- y )
Line 328:
 
23.34375 dup >bin
1011.11101 dup bin>dec [ [I ${} => ${}I] nl ] 2bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 342:
An alternative method is to present the text to the I/O system as with <code>READ (ACARD,*) X</code>, except that there is no facility for specifying any base other than ten. In a more general situation the text would first have to be scanned to span the number part, thus incurring double handling. The codes for hexadecimal, octal and binary formats do ''not'' read or write numbers in those bases, they show the bit pattern of the numerical storage format instead, and for floating-point numbers this is very different. Thus, Pi comes out as 100000000001001001000011111101101010100010001000010110100011000 in B64 format, not 11·0010010000111111011010101... Note the omitted high-order bit in the normalised binary floating-point format - a further complication.
 
The source is F77 style, except for the MODULE usage simply for some slight convenience in sharing DIGIT and not having to re-declare the type of EATNUM. <langsyntaxhighlight Fortranlang="fortran"> MODULE REBASE !Play with some conversions between bases.
CHARACTER*36 DIGIT !A set of acceptable digit characters.
PARAMETER (DIGIT = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") !Not only including hexadecimal.
Line 503:
END DO !On to the next test.
END DO !And another base.
END !Enough of that. </langsyntaxhighlight>
 
Rather than mess about with invocations, the test interprets the texts firstly as base ten sequences, then base two. It makes no complaint over encountering the likes of "666" when commanded to absorb according to base two. The placewise notation is straightforward: 666 = 6x2<sup>2</sup> + 6x2<sup>1</sup> + 6x2<sup>0</sup>
Line 531:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight 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.
Line 576:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 590:
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 630:
s := "1011.11101"
fmt.Printf("%s\t => %v\n", s, binToDec(s))
}</langsyntaxhighlight>
 
{{out}}
Line 640:
=={{header|Haskell}}==
float to binary part only:
<langsyntaxhighlight lang="haskell">import Data.Char (intToDigit)
import Numeric (floatToDigits, showIntAtBase)
 
Line 648:
 
main :: IO ()
main = putStrLn $ dec2bin 23.34375</langsyntaxhighlight>
{{out}}
<pre>
Line 662:
Implementation:
 
<langsyntaxhighlight Jlang="j">b2b=:2 :0
NB. string to rational number
exp=. (1x+y i.'.')-#y
Line 672:
s=. exp&(}.,'.',{.) (":m#.inv mant)-.' '
((exp-1)>.-+/*/\|.s e.'.0') }. s
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> 2 b2b 10 '23.34375'
10111.01011
10 b2b 2 '1011.11101'
11.90625</langsyntaxhighlight>
 
=={{header|Java}}==
Line 685:
Precision is not discussed. Most decimal fractional values are not representable in binary. For example, .1 in decimal is a repeating decimal in binary, with a value of .0[0011]... in binary. As a result, a precision of 50 digits is the default. However, this is a helper method and the actual implementation uses the specified precision.
 
<syntaxhighlight lang="java">
<lang Java>
import java.math.BigDecimal;
import java.math.MathContext;
Line 770:
 
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 783:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">""" Convert numeric string in base 10 to base 2 floating point string """
function dec2bin(x::String)
bx = parse(BigFloat, x)
Line 831:
testdata = ["23.34375", "11.90625", "-23.34375", "-11.90625"]
testconversions(testdata)
</langsyntaxhighlight>{{out}}
<pre>
String (base 10) Base 2 Base 10
Line 841:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
fun decToBin(d: Double): String {
Line 872:
val s = "1011.11101"
println("$s\t => ${binToDec(s)}")
}</langsyntaxhighlight>
 
{{out}}
Line 881:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 978:
print "10111.01011 => $(_fpbin2dec 10111.01011)"
print "1011.11101 => $(_fpbin2dec 1011.11101)"
</syntaxhighlight>
</lang>
{{out}}<pre>
Floating point decimal to Binary conversion:
Line 991:
LiveCode's baseConvert only works on integers.
Only the first part of this task is complete.
<langsyntaxhighlight LiveCodelang="livecode">function float2bin n
put 15 into limit
put 0 into i
Line 1,008:
 
put float2bin(23.34375) // 10111.01011
put float2bin(11.90625) //1011.11101</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Conv2dec=lambda (n$, frombase=10, dp$=".") -> {
Line 1,083:
}
Checkit
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,096:
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
convert(23.34375,binary,decimal);
 
convert(1011.11101,decimal,binary);
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,109:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">dec2bin[x_] := Block[{digits, pos},
{digits, pos} = (RealDigits[ToExpression@x, 2] /. {a_, b_} :> {ToString /@ a, b});
StringJoin @@
Line 1,115:
bin2dec[x_] := FromDigits[RealDigits@ToExpression@x, 2] // N
Print[NumberForm[#, {9, 5}], " => ", dec2bin@#] &@23.34375;
Print[NumberForm[#, {9, 5}], " => ", NumberForm[bin2dec@#, {9, 5}]] &@1011.11101;</langsyntaxhighlight>
{{out}}
<pre>23.34375 => 10111.01011
Line 1,122:
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight Nimlang="nim">import math, strutils
 
func decToBin(f: float): string =
Line 1,147:
echo d, " → ", decToBin(d)
let s = "1011.11101"
echo s, " → ", binToDec(s)</langsyntaxhighlight>
 
{{out}}
Line 1,160:
program should perform conversions from any base to any other base.
{{works with|OCaml|4.03+}}
<langsyntaxhighlight lang="ocaml">
#load "str.cma"
(* Using the interpteter or the compiler:
Line 1,403:
and _ = List.iter (fun tpl -> print_endline (testit tpl)) values
in ()
</syntaxhighlight>
</lang>
{{out}}
23.343750 => 10111.01011; expected 10111.01011 [PASS]
Line 1,431:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 1,450:
 
say dec2bin(23.34375);
say bin2dec('1011.11101');</langsyntaxhighlight>
{{out}}
<pre>10111.01011
Line 1,457:
=={{header|Phix}}==
Handles bases 2..36. Does not handle any form of scientific notation.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">dec_to</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- convert d to a string in the specified base
Line 1,527:
<span style="color: #0000FF;">?</span><span style="color: #000000;">to_dec</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"23.7"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">dec_to</span><span style="color: #0000FF;">(</span><span style="color: #000000;">23.7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,554:
===shorter===
Inspired by Kotlin/Go/Wren (no attempt to handle signs, nor will it handle no-dot properly)
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">dec2bin</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">whole</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trunc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
Line 1,584:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%.5f =&gt; %s =&gt; %.5f\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s =&gt; %.5f =&gt; %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">u</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,593:
=={{header|Python}}==
Python has float.hex() and float.fromhex() that can be used to form our own binary format.
<langsyntaxhighlight lang="python">hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))
 
Line 1,626:
hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]
+ str(int('0b' + bn2[p+2:], 2)))
return float.fromhex(hx)</langsyntaxhighlight>
 
{{out}}
Line 1,647:
=={{header|Racket}}==
The binary to number conversion is easy because it's supported by Racket. We can use <code>string-&gt;number</code>, wrap it in a dedicated function or use the read extension.
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (string->number/binary x)
Line 1,657:
#b0.01
(string->number "0.01" 2)
(newline)</langsyntaxhighlight>
{{out}}
<pre>2.3125
Line 1,665:
0.25</pre>
Racket only supports the number to binary conversion for integer numbers, so we multiply the original number by a power of two, to get all the binary digits, and then we manipulate the string to place the point in the correct place.
<langsyntaxhighlight Racketlang="racket">(define (number->string/binary x)
(define decimals-places 10)
(define digits-all (~r (inexact->exact (round (* x (expt 2 decimals-places))))
Line 1,684:
(number->string/binary 9)
(number->string/binary 0.01)
(newline)</langsyntaxhighlight>
{{out}}
<pre>"1001.000000101"
Line 1,690:
"0.000000101"</pre>
Some additional interesting examples
<langsyntaxhighlight Racketlang="racket">(number->string/binary (string->number/binary "010110.0011010"))
(string-&gt;number/binary (number->string/binary .1))
(newline)
 
(number->string/binary (string->number/binary "0.11111111111"))
(string->number/binary "0.11111111111")</langsyntaxhighlight>
{{out}}
<pre>"10110.001101000"
Line 1,705:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>given "23.34375" { say "$_ => ", :10($_).base(2) }
given "1011.11101" { say "$_ => ", :2($_).base(10) }</langsyntaxhighlight>
{{out}}
<pre>23.34375 => 10111.01011
Line 1,748:
This REXX program can handle any sized number &nbsp; (as per the number of digits/numerals) &nbsp; that can be entered at the
<br>command line.
<langsyntaxhighlight lang="rexx">/*REXX pgm converts any number in a base to another base including fractions; bases≤242.*/
parse arg number toBase inBase digits . /*obtain optional arguments from the CL*/
if toBase=='' | toBase=="," then toBase= 10 /*Not specified? Then use the default.*/
Line 1,818:
return oS || word( strip( space(w), 'L', 0)strip( strip(g, , 0), "T", .) 0, 1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error***: ' arg(1); say; exit 13</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 23.34375 &nbsp; 2 </tt>}}
<pre>
Line 1,833:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 08.02.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 1,900:
If res<>soll Then
Say 'soll='soll
Return</langsyntaxhighlight>
'''Output:'''
<pre>23.34375 -> 10111.01011
Line 1,908:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
decimals(5)
 
Line 1,982:
 
see "" + numdec + "." + numdig
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,990:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def dec2bin(dec, precision=16) # String => String
int, df = dec.split(".")
minus = int.delete!("-")
Line 2,026:
dec2 = bin2dec(bin)
puts "%10s => %12s =>%10s" % [dec, bin, dec2]
end</langsyntaxhighlight>
 
{{out}}
Line 2,038:
=={{header|Scala}}==
===Idiomatic (FP with tailrec)===
<langsyntaxhighlight Scalalang="scala">import java.lang.Long
 
import scala.annotation.tailrec
Line 2,076:
println( { def s = "1011.11101"; s"$s\t => ${binToDec(s)}" } )
}
}</langsyntaxhighlight>
{{Out}}Experience running it in your browser by [https://scastie.scala-lang.org/auzWgFqCRBaYoOaJV92tgw Scastie (remote JVM)].
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func dec2bin(String n) {
Num(Num(n, 10).base(2), 10)
}
Line 2,089:
 
with("23.34375") { |s| say (" #{s} => ", dec2bin(s)) }
with("1011.11101") { |s| say ( "#{s} => ", bin2dec(s)) }</langsyntaxhighlight>
{{out}}
<pre>
Line 2,099:
By far the easiest way to do this is to use Tcl's built-in handling of IEEE arithmetic, converting the IEEE representation into the string representation we want (and ''vice versa'') by simple string manipulations.
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
proc dec2bin x {
Line 2,156:
set d [bin2dec $b]
puts "$case => $b => $d"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,176:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Conv, Fmt
 
var decToBin = Fn.new { |d|
Line 2,207:
Fmt.print("$g\t => $s", f, decToBin.call(f))
var s = "1011.11101"
Fmt.print("$s\t => $g", s, binToDec.call(s))</langsyntaxhighlight>
 
{{out}}
Line 2,217:
=={{header|zkl}}==
Rather limited.
<langsyntaxhighlight lang="zkl">fcn bin2float(bstr){ // no exponents
bstr=bstr.strip();
m:=bstr[0,1]=="-"; if(m)bstr=bstr[1,*]; m=m and -1 or 1;
a,b:=bstr.split(".").apply(fcn(s){ s and s or 0 }).append(0,0);
(a.toInt(2).toFloat() + b.toInt(2).toFloat()/(2).pow(b.len()))*m
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach bstr in (T("1011.11101","0.01","0.11111111111","-.1","","1")){
println(bstr," --> ",bin2float(bstr).toString(20))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,235:
1 --> 1
</pre>
<langsyntaxhighlight lang="zkl">fcn float2bin(x,digitsOfPrecision=20){
m,zeros:="","0"*digitsOfPrecision;
if(x<0){ m="-"; x=-x }
Line 2,243:
if(z:=b.reverse().prefix(zeros)) b=b[0,-z]; // remove trailing zeros
String(m,a.toString(2),".",b);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach x in (T(23.34375,(0.0).pi,-33.8,0.1,0.15625)){
println(x," --> ",s:=float2bin(x)," --> ",bin2float(s).toString(20));
}</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits