HexEncoding (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the creation of a class named THexEncoding, derived from the TEncoding class. The methods you need to implement are GetByteCount, GetBytes, GetCharCount, GetChars, GetMaxByteCount, GetMaxCharCount, and GetPreamble.

Code

type
  THexEncoding = class(TEncoding)
  strict protected
    function GetByteCount(Chars: PChar; CharCount: Integer): Integer; overload; override;
    function GetBytes(Chars: PChar; CharCount: Integer; Bytes: PByte; ByteCount: Integer): Integer; overload; override;
    function GetCharCount(Bytes: PByte; ByteCount: Integer): Integer; overload; override;
    function GetChars(Bytes: PByte; ByteCount: Integer; Chars: PChar; CharCount: Integer): Integer; overload; override;
  public
    function GetMaxByteCount(CharCount: Integer): Integer; override;
    function GetMaxCharCount(ByteCount: Integer): Integer; override;
    function GetPreamble: TBytes; override;
  end;

function THexEncoding.GetByteCount(Chars: PChar; CharCount: Integer): Integer;
begin
  { The result is the number of characters multiplied by 2 times the size of the char type. }
  Result := CharCount * SizeOf(Char) * 2;
end;

function THexEncoding.GetBytes(Chars: PChar; CharCount: Integer; Bytes: PByte; ByteCount: Integer): Integer;
begin
  { The BinToHex method converts a binary value to its hexadecimal representation. }
  BinToHex(Chars, PAnsiChar(Bytes), CharCount * SizeOf(Char) * 2);
  { This function returns nothing. }
end;

function THexEncoding.GetCharCount(Bytes: PByte; ByteCount: Integer): Integer;
begin
  { The result of this funcion is the number of bytes divided by 2. }
  Result := ByteCount div 2;
end;

function THexEncoding.GetChars(Bytes: PByte; ByteCount: Integer; Chars: PChar; CharCount: Integer): Integer;
begin
  { The HexToBin method converts a hexadecimal value to its binary representation. }
  HexToBin(PAnsiChar(Bytes), Chars, ByteCount div SizeOf(Char));
  { This function returns nothing. }
end;

function THexEncoding.GetMaxByteCount(CharCount: Integer): Integer;
begin
  { The result of this function is the number of chars multiplied by 2. }
  Result := CharCount * 2;
end;

function THexEncoding.GetMaxCharCount(ByteCount: Integer): Integer;
begin
  { The result is the number of bytes divided by 2. Add a 1 for safety reasons. }
  Result := (ByteCount div 2) + 1;
end;

function THexEncoding.GetPreamble: TBytes;
begin
  { The result is nil because the use of a preamble is not supported. }
  Result := nil;
end;

Uses

Personal tools
Assistance