首页 > 代码库 > XE6 ShortString与String相互转换
XE6 ShortString与String相互转换
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.
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。