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.