16,748
社区成员
发帖
与我相关
我的任务
分享
// 把字符串转换为16进制字符串
// 如:a变成61(即10进制的97);abc变成616263
function stringToHex(const s: AnsiString): AnsiString;
const
hexes: array [0..$f] of AnsiChar = ('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
var
I, iLen: Integer;
begin
iLen := Length(s);
SetLength(Result, iLen * 2);
for I := 0 to iLen - 1 do begin
Result[I * 2 + 1] := hexes[Byte(s[i+1]) shr 4];
Result[I * 2 + 2] := hexes[Byte(s[i+1]) and $f];
end;
end;
// 16进制字符串转换为字符串
// 如:61(即10进制的97)变成a;616263变成abc
function HexTostring(const s: AnsiString): AnsiString;
var
I, iLen: Integer;
C0,C1: AnsiChar;
B0,B1: Word;
begin
iLen := Length(s);
SetLength(Result, iLen div 2);
I := 0;
while iLen > I do begin
C0 := S[I+1];
C1 := S[I+2];
case C0 of
'1'..'9': B0 := Byte(C0) - 48;
'a'..'f': B0 := Byte(C0) - 97 + 10;
'A'..'F': B0 := Byte(C0) - 65 + 10;
else
B0 := 0;
end;
case C1 of
'1'..'9': B1 := Byte(C1) - 48;
'a'..'f': B1 := Byte(C1) - 97 + 10;
'A'..'F': B1 := Byte(C1) - 65 + 10;
else
B1 := 0;
end;
Result[I div 2 + 1] := AnsiChar(B0 shl 4 or B1);
Inc(I, 2);
end;
end;
var
s1, s2, S3: AnsiString;
begin
s1 := 'abc123';
s2 := stringToHex(s1);
S3 := HexTostring(S2);
ShowMessage(Format('S1="%s"'#13#10'S2="%s"'#13#10'S3="%s"',[s1,s2,S3]));
end;
function DataToHex(Data: PChar; Len: integer): string;
//把指定的二进制数据转换成十六进制表示的字符串
begin
SetLength(Result, Len shl 1);
BinToHex(Data, PChar(Result), Len);
end;
function HexToData(const HexStr: string): string;
//转换十六进制字符串数据为字符串
begin
SetLength(Result, Length(HexStr) shr 1);
Classes.HexToBin(PChar(HexStr), PChar(Result), Length(Result));
end;