Преобразование ASCII в шестнадцатиричное представление



Строка представляет собой массив байтов в виде ASCII-символов. Необходимо организовать преобразование типов по аналогии с Delphi-функциями Ord и Chr.

Функция BytesToHexStr преобразует, к примеру, набор байтов [0,1,1,0] в строку '30313130', HexStrToBytes выполнит обратное преобразование.


unit Hexstr;
interface
uses String16, SysUtils;
type
PByte = ^BYTE;
procedure BytesToHexStr(var hHexStr: string; pbyteArray: PByte; InputLength:
WORD);
procedure HexStrToBytes(hHexStr: string; pbyteArray: Pointer);
procedure HexBytesToChar(var Response: string; hexbytes: PChar; InputLength:
WORD);
implementation
procedure BytesToHexStr(var hHexStr: string; pbyteArray: PByte; InputLength:
WORD);
const
HexChars: array[0..15] of Char = '0123456789ABCDEF';
var
i, j: WORD;
begin
SetLength(hHexStr, (InputLength * 2));
FillChar(hHexStr, sizeof(hHexStr), #0);
j := 1;
for i := 1 to InputLength do
begin
hHexStr[j] := Char(HexChars[pbyteArray^ shr 4]);
inc(j);
hHexStr[j] := Char(HexChars[pbyteArray^ and 15]);
inc(j);
inc(pbyteArray);
end;
end;
procedure HexBytesToChar(var Response: string; hexbytes: PChar; InputLength:
WORD);
var
i: WORD;
c: byte;
begin
SetLength(Response, InputLength);
FillChar(Response, SizeOf(Response), #0);
for i := 0 to (InputLength - 1) do
begin
c := BYTE(hexbytes[i]) and BYTE($F);
if c > 9 then
Inc(c, $37)
else
Inc(c, $30);
Response[i + 1] := char(c);
end; {for}
end;
procedure HexStrToBytes(hHexStr: string; pbyteArray: Pointer);
{pbyteArray указывает на область памяти, хранящей результаты}
var
i, j: WORD;
tempPtr: PChar;
twoDigits: string[2];
begin
tempPtr := pbyteArray;
j := 1;
for i := 1 to (Length(hHexStr) div 2) do
begin
twoDigits := Copy(hHexStr, j, 2);
Inc(j, 2);
PByte(tempPtr)^ := StrToInt('$' + twoDigits);
Inc(tempPtr);
end; {for}
end;
end.


unit String16.
interface
{$IFNDEF Win32}
procedure SetLength(var S: string; Len: Integer);
procedure SetString(var Dst: string; Src: PChar; Len: Integer);
{$ENDIF}
implementation
{$IFNDEF Win32}
procedure SetLength(var S: string; Len: Integer);
begin
if Len > 255 then
S[0] := Chr(255)
else
S[0] := Chr(Len)
end;
procedure SetString(var Dst: string; Src: PChar; Len: Integer);
begin
if Len > 255 then
Move(Src^, Dst[1], 255)
else
Move(Src^, Dst[1], Len);
SetLength(Dst, Len);
end;
{$ENDIF}
end.


Далее: Преобразование HTML в RTF »»