Thursday, February 28, 2008

Hexadecimal to Binary Converter (Pascal)


program meng-konversikan bilangan heksadesimal (basis 16)
menjadi bilangan biner (basis 2)

uses crt;

var

hexa : string;{variable for storing hexa input}

biner : string;{variable for storing binary output}

desimal : integer;{temporary variable for decimal conversion}

index,conv,sub : integer;{variable for looping and subtractor}



BEGIN

clrscr;{clearing the screen}

{ask for hexa input and read the input}

write('Input on Hexa : ');readln(hexa);

{primary loop converter hexa to binary}

for index:=1 to length(hexa) do

begin

{case of hexa written on numeric character}

if (ord(hexa[index])>=ord('0')) and (ord(hexa[index])<=ord('9')) then begin {ascii code of hexa - ascii code of '0'} desimal:=ord(hexa[index])-ord('0'); end else {case of hexa written on uppercase letter} if (ord(hexa[index])>=ord('A')) and (ord(hexa[index])<=ord('F')) then begin {ascii code of hexa - ascii code of 'A'+10} {A represent 10 on decimal} desimal:=ord(hexa[index])-ord('A')+10; end else {case of hexa written on lowercase letter} if (ord(hexa[index])>=ord('a')) and (ord(hexa[index])<=ord('f')) then begin {ascii code of hexa - ascii code of 'a'} desimal:=ord(hexa[index])-ord('a')+10; end else {case of the input is wrong} begin writeln('INPUTAN SALAH!!'); readln; {terminate the program immediately} exit; end; writeln('BINARY'); {the subtractor start on 8 (2^3)} sub:=8; for conv:=3 downto 0 do begin {the decimal bigger than subtractor} if (desimal>=sub) then

begin

write('1');

{subtract the decimal with subtractor}

desimal:=desimal-sub;

end

else

begin

{write 0 and do nothing}

write('0');

end;

{decrement the power of subtractor by 1}

sub:=sub div 2;

end;

{just for separating output per character}

write(' ');

end;

readln;

END.

No comments: