program Project1;
uses
SysUtils, StrUtils;
type
ByteArray = array of Byte;
function ByteArrayToStr(const BA: ByteArray): String;
var
i: Integer;
S: String;
begin
Result := '';
if Length(BA) = 0 then exit;
SetLength(Result, Length(BA) shl 1);
if BA = nil then exit;
for i := low(BA) to high(BA) do
begin
S := IntToHex(Ba[i]);
Move(S[1], Result[1 + i shl 1], 2);
end;
end;
function StrToByteArray(const S: String): ByteArray;
var
i: Integer;
aCount: Integer;
aStr: String;
begin
if S = '' then Result := nil
else
begin
aCount := length(S) shr 1;
Setlength(Result, aCount);
for i := 0 to aCount - 1 do
begin
aStr := Copy(S, i shl 1 + 1, 2);
Result[i] := Hex2Dec(aStr);
end;
end;
end;
function ByteArrayToStr_v2(const BA: ByteArray): String;
const
hex: String[16] = '0123456789ABCDEF';
var
i, l: Integer;
begin
Result := '';
SetLength(Result, Length(BA) * 2);
for i := low(BA) to high(BA) do
begin
Result[i * 2 + 1] := hex[BA[i] div 16 + 1];
Result[i * 2 + 2] := hex[BA[i] and 15 + 1];
end;
end;
function StrToByteArray_v2(const S: String): ByteArray;
var
i, l: Integer;
st: String;
begin
l := Length(S) div 2;
SetLength(Result, l);
SetLength(st, 2);
for i := 0 to l - 1 do
Result[i] := StrToInt('$' + S[i * 2 + 1] + S[i * 2 + 2]);
end;
var
BA, barr: ByteArray;
S: String;
i, x: Integer;
cs: Int64;
count: Integer = 1000000;
begin
SetLengtH(barr, 7);
for i := Low(barr) to high(barr) do
barr[i] := i + 1;
Writeln('------ org ------');
cs := GetTickCount64;
for x := 1 to count do
begin
S := ByteArrayToStr(barr);
BA := StrToByteArray(S);
end;
Writeln('org time in ms: ', GetTickCount64 - cs);
S := ByteArrayToStr(barr);
BA := StrToByteArray(S);
Writeln(S);
for i := low(BA) to high(Ba) do
writeln(i + 1, ' ', BA[i]);
Writeln('------ v2 ------');
cs := GetTickCount64;
for x := 1 to count do
begin
S := ByteArrayToStr_v2(barr);
BA := StrToByteArray_v2(S);
end;
Writeln('v2 time in ms: ', GetTickCount64 - cs);
S := ByteArrayToStr_v2(barr);
BA := StrToByteArray_v2(S);
Writeln(S);
for i := low(BA) to high(Ba) do
writeln(i + 1, ' ', BA[i]);
Writeln;
Writeln('hit key when ready.');
readln;
end.