Type
TmStream = class(TMemoryStream)
public
procedure LoadFromString(AText: String);
function SaveToString: String;
function ToHexStr: string;
procedure LoadFromHexStr(const Hex: string);
end;
implementation
{ TmStream }
procedure TmStream.LoadFromString(AText: String);
begin
Clear;
if Length(AText) = 0 then
Exit;
SetSize(Length(AText) div 2);
HexToBin(PWideChar(AText), PAnsiChar(Self.Memory), Length(AText) div 2);
Position := 0;
end;
function TmStream.SaveToString: String;
begin
SetLength(Result, Size * 2);
BinToHex(PAnsiChar(Self.Memory), PWideChar(Result), Size);
end;
function TmStream.ToHexStr: string;
const
Convert: array [0 .. 15] of Char = '0123456789ABCDEF';
var
i, p: integer;
B: byte;
Buf: TStream;
begin
Buf := Self;
SetLength(Result, Buf.Size * 2);
p := Buf.Position;
Buf.Position := 0;
for i := 1 to Buf.Size do
begin
Buf.Read(B, 1);
Result[(i * 2) - 1] := Convert[B shr $4];
Result[(i * 2)] := Convert[B and $F];
end;
Buf.Position := p;
end;
procedure TmStream.LoadFromHexStr(const Hex: string);
const
Convert: array ['0' .. 'f'] of SmallInt = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13,
14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10,
11, 12, 13, 14, 15);
var
i, p: integer;
B: byte;
Buf: TStream;
begin
Buf := Self;
if Buf.Size < Length(Hex) div 2 then
Buf.Size := Length(Hex) div 2;
p := Buf.Position;
Buf.Position := 0;
i := 1;
while i <= Length(Hex) do
begin
if not(Hex[i] in ['0' .. 'f']) or not(Hex[i + 1] in ['0' .. 'f']) then
Break;
B := byte((Convert[Hex[i]] shl 4) + Convert[Hex[i + 1]]);
Buf.Write(B, 1);
Inc(i, 2);
end;
Buf.Position := p;
end;
end.