Sunday, February 14, 2010

Binary translator in Pascal

I represent a sample code of a binary translator algorithm. If you have any questions don't hesitate to leave a comment. Thank you!


Program
binary;
uses crt;
Type
pin=Array[0..14] of Integer;
var
number:Integer;
bintbl,result:pin;
ans:integer;
bnr:string;

Function power_of_2(power:integer):Integer;
var i,p:integer;
begin
p:=1;
for i:=1 to power do
p:=p*2;
power_of_2:=p
end;


Function bin(num:Integer):String;
var iplp,i:integer;
begin
repeat

iplp:=num mod 2;
if iplp=0 then
bin:='0'+bin
else
bin:='1'+bin;
num:=num div 2;
until num=0;
end;


Function cint(b:string):integer;
begin
if b='1' then
cint:=1 else cint:=0; end;



Procedure put_in(Var bl:pin; s:string);
var i:integer;
begin
for i:=0 to length(s)-1 do
bl[i]:=cint(COPY(s,length(s)-i,1));
end;


Function normal(bl:pin):integer;
var i:integer;
begin
normal:=0;
for i:=14 downto 0 do
if bl[i]=1 then
normal:=normal+power_of_2(i);
end;



Procedure print_result(res:pin);
var i:integer;
begin
for i:=14 downto 0 do
write(res[i]);
end;

begin
repeat
clrscr;
writeln('Binary Translator');
writeln;
writeln('What do you want to do?');
writeln;
writeln('1. Binary->normal');
writeln('2. Normal->binary');
writeln('3. Exit');
writeln;
readln(ans);
case ans of
1:begin
writeln('Give the binary');
repeat
readln(bnr);
until length(bnr)<=14; put_in(bintbl,bnr); writeln('The number is'); writeln(normal(bintbl)); print_result(bintbl); readln; readln; end;
2:begin

writeln('Give a positive number');
writeln;
readln(number);
writeln(bin(number));
prepare;
readln;
end;


end;
until ans=3;


clrscr;
writeln('By vaslabs');
writeln('Author: Vasilis Nicolaou');
readln;
end.

No comments:

Post a Comment