delphi中有直接把10进制转换成16进制的函数:
function IntToHex(Value: Integer; Digits: Integer): string; overload; function IntToHex(Value: Int64; Digits: Integer): string; overload;
使用方法为:
procedure TForm1.Button1Click(Sender: TObject); var i,m: Integer; begin Label1.Caption := ''; for i := 1 to Length(Edit1.Text) do begin
m := StrToInt(Edit1.Text[i])); edit2 := IntToHex(StrToInt(Edit1.Text[i]),2)+ ''; edit3 := IntToHex(m,2);
end; end;
然而,delphi中却没有把16进制直接转换成10进制的函数,将16进制转换成10进制需要自己定义函数,这是自己编写的一个,不当之处还请指出:
unit Unit1; { 16进制与10进制的相互转换 } interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type TForm1 = class(TForm) Edit1: TEdit; Label1: TLabel; Label2: TLabel; Edit2: TEdit; Button1: TButton; Button2: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject);
private function HexToInt(str:string):word; public { Public declarations } end;
var Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject); begin edit1.Clear; edit2.Clear; end;
procedure TForm1.Button1Click(Sender: TObject); var str : string; begin if edit1.Text<>'' then if edit2.Text<>'' then begin messageBox(handle,'只能输入一个数字,请重新输入','警告',MB_ok); edit1.Clear; edit2.Clear; end else begin edit2.Text:= IntToHex(strtoint(edit1.Text),4); end else if edit2.text='' then begin messageBox(Handle,'请输入数字','警告!',MB_ok); end else begin str := edit2.Text ; edit1.Text := IntToStr(HexToInt(str)); end; end;
function TForm1.HexToInt (str:string) : word; var i , value : word; pos : word;
begin value:=0; pos:=length(str); for i:=1 to pos do begin case str[i] of 'f','F': value := value*16+15; 'e','E': value := value*16+14; 'd','D': value := value*16+13; 'c','C': value := value*16+12; 'b','B': value := value*16+11; 'a','A': value := value*16+10; '0'..'9': value := value*16+ord(str[i])-ord('0'); else result:=value; exit; end; result:=value; end; end;
procedure TForm1.Button2Click(Sender: TObject); begin Application.Terminate; close; end;
end.
|
请发表评论