ShortStringToString (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

Here is an example code declaring two routines, ShortStringtoString() and StringToShortString(). These routines facilitate converting data from the old ShortString format to the current default String type (that is, UnicodeString). You might need to make such conversions in order to move Delphi code from desktop to the iOS platform.

Notice the use of TEncoding.Ansi.GetString() and TEncoding.Ansi.GetBytes() to convert character data.

Code

program Test;
{$APPTYPE CONSOLE}
uses
  System, System.SysUtils;
  
const
  Value: array[0..5] of Byte = (5, 72, 101, 76, 76, 111);  { Old ShortString representation of 'Hello' }

type
  EShortStringConvertError = class(Exception)
  end;
  
function ShortStringToString(Value: array of Byte): String;
var
  B: TBytes;
  L: Byte;
begin
  Result := '';
  L := Value[0];
  SetLength(B, L);
  Move(Value[1], B[0], L);
  Result := TEncoding.Ansi.GetString(B);
end;

procedure StringToShortString(const S: String; var RetVal);
var
  L: Integer;
  I: Byte;
  C: Char;
  P: PByte;
  B: TBytes;
begin
  L := Length(S);
  if L > 255 then
    raise EShortStringConvertError.Create('Strings longer than 255 characters cannot be converted');
  SetLength(B, L);
  P := @RetVal;
  P^ := L;
  Inc(P);
  B := TEncoding.Ansi.GetBytes(S);
  Move(B[0], P^, L); 
end;

procedure DoTest;
var
  S: String;
  OldS: array[0..17] of Byte;  // Replacing string[17]
begin
  S := ShortStringToString(Value);
  WriteLn('#1 S=', S);
  S := 'Excellence';
  StringToShortString(S, OldS);
  S := '';
  S := ShortStringToString(OldS);
  WriteLn('#2 S=', S);
end;

begin
  try
    DoTest;
  except
    on E: Exception do
      begin
        WriteLn('FAIL - Unexpected Exception');
        WriteLn('  ClassName=', E.ClassName);
        WriteLn('    Message=', E.Message);
      end;
  end;
end.

Uses

See Also

Personal tools
Assistance