Decimal floating point number to binary: Difference between revisions

Added Ada solution
m (syntax highlighting fixup automation)
(Added Ada solution)
Line 41:
23.34375 => 10111.01011
1011.11101 => 11.90625
</pre>
 
=={{header|Ada}}==
 
<syntaxhighlight lang="ada">
-- Decimal floating point number to binary (and vice versa)
-- J. Carter 2023 Apr
-- We'll presume the input is a string containing the image of the number in the appropriate base, and the output is the
-- image in the other base; using the language's conversion of numeric literals seems like cheating
-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC)
 
with Ada.Strings.Fixed;
with Ada.Text_IO;
with PragmARC.Unbounded_Numbers.Rationals;
 
procedure Dec_Bin_FP is
use PragmARC.Unbounded_Numbers.Rationals; -- Avoid losing any precision in the inputs
 
function To_Binary (Decimal : in String) return String is
(Image (Value (Decimal), Base => 2) );
 
function To_Decimal (Binary : in String) return String is
(Image (Value ("2#" & Binary & '#') ) );
 
Decimal : constant String := "23.34375";
Binary : constant String := "1011.11101";
Pi : constant String := "3.14159265358979323846264338327950288419716939937511";
begin -- Dec_Bin_FP
Ada.Text_IO.Put_Line (Item => Decimal & ' ' & To_Binary (Decimal) );
Ada.Text_IO.Put_Line (Item => Binary & ' ' & To_Decimal (Binary) );
Ada.Text_IO.Put_Line (Item => Pi & ' ' & To_Binary (Pi) );
end Dec_Bin_FP;
</syntaxhighlight>
 
{{out}}
<pre>
23.34375 10111.01011
1011.11101 11.90625
3.14159265358979323846264338327950288419716939937511 11.0010010000111111011010101000100010000101101000110000100011010011000100110001100110001010001011100000001101110000011100110100010010100100000010010011100000100010001010110010111101110111001101010111010110100001001100011101010110011100010011100000101110011010001111000010101010101101011011001000010100111011100010111000010011101110010100111100011001101011101101111111010101100100010110111101011100101101100101000100100011001011011000011001000011110100001101001011101001101101110101010011000110010100100000010010000111111110011000000000010101110110001110001110010110111000101110001010110101110111011001010111010111101111011110000101011000110010101011101010110110100011110010110101111111011111010110111101100111101111011011001101011010110011010110000010011100110000001011100111000110011001111000001000001101110100000010000110110000000110001001010111011110011000110010100010010100101000000011101001111010101011001000101010001111101001110110010101101110110110000000000011110111110011110101011010000101001010
</pre>
 
30

edits