16进制转10进制
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
function HexToDec(const value:Integer):string;
function Hex2Dec(const value:integer):string;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
bytes:array of Byte;
procedure TForm1.Button1Click(Sender: TObject);
begin
SetLength(bytes,8);
bytes[0]:=$01;
bytes[1]:=$03;
bytes[2]:=$02;
bytes[3]:=$00;
bytes[4]:=$0B;
bytes[5]:=$19;
bytes[6]:=$BF;
bytes[7]:=$0C;
Memo1.Lines.Add(HexToDec(bytes[5])); //bytes=(1,3,2,0,11,25,191,12) 分别对应十六进制$01 $03 $02 $00 $0B $19 $BF $0C 的字节码
Memo1.Lines.Add(Hex2Dec(Bytes[5]));
end;
function TForm1.Hex2Dec(const value: integer): string;
const hex:array['A'..'F'] of Integer=(10,11,12,13,14,15); //定义数组与集合对应关系
var
str:string;
ln:Integer;
i:Integer;
begin
str:=UpperCase(IntToStr(value)); //把字节码转换成字符串 如25=>'25'
ln:=0;
for i:=1 to Length(str) do //遍历数组 str[1]='2' str[2]=5
begin
if str[i]<'A' then
// ln:=ln*16+ord(str[i])-48 //48 对应字节码 0 此处也可以写成ln*16+strtoint(str[i])
ln:=ln*16+strtoint(str[i])
else
ln:=ln*16+hex[str[i]]; //计算整个字节的值
end;
result:=IntToStr(ln);
end;
//16进制转10进制
function TForm1.HexToDec(const value: Integer): string;
var
s:string;
begin
s:='$'+inttostr(value); //字节码转换成字符串 $25 十六进制字符串
result:=IntToStr(StrToInt(s)); //字节码字符串转换成数值 如 strtoint('$25')=37
end;
end.