星五博客

Delphi中的进制转换

Delphi中的几种进制转换函数

非原创,收藏供查询。

二进制转换

function binToDec(Value: string): integer;
var
  str: string;
  i: integer;
begin
  Str := UpperCase(Value);
  result :=0;
for i :=1to Length(str) do
    result := result *2+ ORD(str[i]) -48;
end;

functionmod_num(n1, n2: integer): integer; //取余数
begin
  result := n1 - n1 div n2 * n2
end;

function reverse(s: string): string; //取反串
var
  i, num: Integer;
  st: string;
begin
  num := Length(s);
  st :='';
for i := num downto1do
begin
    st := st + s[i];
end;
  Result := st;
end;

function DecTobin(Value: Integer): string; //十进制转化二进制
var
  ST: string;
  N: Integer;
begin
  ST :='';
  n := value;
while n >=2do
begin
    st := st + IntToStr(mod_num(n, 2));
    n := n div2;
end;
  st := st + IntToStr(n);
  Result := reverse(st);
end;

16进制转字符

function   HexToChar(Str:   string):   string;   
var
      i:   integer;   
      buf1:   array[0..100]   of   byte;   
begin
for   i   :=0to   (length(Str)   div2-1)   do
begin
          buf1[i]   :=   strtoint('$'+   copy(Str,   i   *2+1,   2));   
          Result   :=   Result   +   char(buf1[i]);   
end;   
end;   

function   CharToHex(Str:   string):   string;   
var
      i:   integer;   
      ch:   char;   
begin
for   i   :=1to   (length(str))   do
begin
          ch   :=   Str[i];   
          Result   :=   Result   +   inttohex(byte(ch),   2);   
end;   
end;

16进制转十进制

function hextoint(s: string): Integer;
begin//$代表16进制
  Result:=StrToInt('$'+s);
end;

数据转换成二进制

function conertde(s:string):string; 
var//数据都是以二进制的形式保存
i:integer; 
begin
for i:=1to length(s) do
   result:=result+inttohex(ord(s[i]),2); 
end;

Delphi