M
M
masterrr2011-12-05 19:48:18
Number systems
masterrr, 2011-12-05 19:48:18

The fastest algorithm dec -> bin in Pascal?

Tell me, please, what is the fastest algorithm for converting a number to binary from decimal can be implemented in Pascal?
There are already options:
1. Recursion:

function bin(a: integer):integer;<br>
begin<br>
     if a>=2 then<br>
        bin(a div 2);<br>
     write(a mod 2);<br>
end;

2. "Game" with strings:
while n>0 do begin<br>
  if n mod 2 = 0 then<br>
    s:=s+'0'<br>
  else begin<br>
    s:=s+'1';<br>
    n:=n-1;<br>
  end;<br>
  n:=n div 2;<br>
end;<br>
for i:=length(s) downto 1 do<br>
  write(s[i]);<br>
end;

3. And the most common, simple solution to the problem:
while a>=1 do<br>
  begin<br>
    i:=i+1;<br>
    b[i]:=a mod 2;<br>
    a:=a div 2;<br>
  end;<br>
n:=i;<br>
for i:=n downto 1 do<br>
write(b[i]);<br>

Memory consumption is not important, execution time and the ability to translate int64 numbers are important (-9223372036854775808..9223372036854775807)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
anmipo, 2011-12-05
@masterrr

Obvious optimization:

b[i]:=a and 1;
a:=a shr 1;
Although the compiler has to guess.

W
Wott, 2011-12-05
@Wott

well, if memory consumption is not important, then the table will be the fastest :)

G
Gribozavr, 2011-12-05
@gribozavr

Where are the decimals? There are machine numbers, they are already binary.

Y
YourChief, 2011-12-05
@YourChief

Have you tried benchmarking all three?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question