[ Binary -> Decimal ]
function Pow( i, k : Integer): Integer;
var
j,
liCount : Integer;
begin
if k > 0 then
j := 2
else
j := 1;
for liCount := 1 to k - 1 do
j := j * 2;
Result := j;
end;
function BinToDec( Str : String ) : Integer;
var
i,
Len,
Res : Integer;
Error: Boolean;
begin
Error := False;
Len := Length( Str );
Res := 0;
for i := 1 to Len do
if ( Str[ i ] = '0' ) OR
( Str[ i ] = '1' ) then
Res := Res + Pow( 2, Len - i ) * StrToInt( Str[ i ] )
else
begin
MessageDlg( 'It is not a binary number', mtInformation, [ mbOK ], 0 );
Error := True;
Break;
end;
if Error = True then
Result := 0
else
Result := Res;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if Edit1.Text<>'' then
Label2.Caption:=IntToStr( BinToDec( Edit1.Text ) );
end;
[ Decimal -> Binary ]
function TForm1.DecToBinStr( N : Integer ) : string;
var
S: string;
i: Integer;
Negative: Boolean;
begin
if N<0 then Negative:=True;
N:=Abs(N);
for i:=1 to SizeOf(N)*8 do
begin
if N<0 then S:=S+'1'
else S:=S+'0';
N:=N shl 1;
end;
Delete(S,1,Pos('1',S)-1);
if Negative then S:='-'+S;
Result:=S;
end;
|