Delphi的二進制與八進制、十進制、十六進制轉換

uses Math;

 

//  二進制 --> 十進制

function BinToTen(s: string): Extended;
var
  I, iLen: Integer;
begin
  Result := 0;
  iLen := Length(s);
  for I := 0 to iLen - 1 do
    Result := Result + StrToInt(s[iLen - I]) * Power(2, I);
end;

 

 

// 十進制 --> 二進制

function TenToBin(I: Integer): string;
var
  iMod, iDiv: Integer;
begin
  Result := '';
  while I > 0 do
  begin
    iDiv := I div 2;
    iMod := I mod 2;
    I := iDiv;
    Result := IntToStr(iMod) + Result;
  end;
end;

 

 

 

// 二進制,八進制,十六進制 ---> 十進制

function XXXToTen(s: string; base: Byte): Extended;
var
  I, iLen: Integer;
const
  Convert: string = '0123456789ABCDEF';
begin
  Result := 0;
  s := UpperCase(s);
  iLen := Length(s);
  if base = 16 then
  begin
    for I := 0 to iLen - 1 do
      Result := Result + (Pos(s[iLen - I], Convert) - 1) * Power(base, I);
  end
  else
  begin
    for I := 0 to iLen - 1 do
      Result := Result + StrToInt(s[iLen - I]) * Power(base, I);
  end;
end;

 

//十進制 -->二進制,八進制,十六進制

function TenToXXX(I: Integer; base: Byte): string;
var
  iMod, iDiv: Integer;
const
  Convert: array[0..15] of Char = '0123456789ABCDEF';
begin

  Result := '';
  while I > 0 do
  begin
    iDiv := I div base;
    iMod := I mod base;
    I := iDiv;
    if base = 16 then
      Result := Convert[iMod] + Result
    else
      Result := IntToStr(iMod) + Result;
  end;
end;

 

 

 

posted on 2010-03-29 16:14  markwu  阅读(681)  评论(0编辑  收藏  举报

导航