• Delphi 中String、ANSIString、TBytes之间的转换


    这个问题要从最近一个项目谈起,服务器端要求UTF8编码,Delphi内部是UTF16编码,为了避免风险我将代码中数据都定义为AnsiString,但实际还是除了些问题。

    delphi7下

    buffer是tbytes型,temp是string型

    temp := string(pointer(buffer));
    setlength(temp,length(buffer));
    CopyMemory(Pointer(temp), @buffer[0], Length(buffer));
    到了XE后,也许经过dot Net洗礼后,下面的代码更好理解,当然这是站在开发者的角度。
    var
      Buf : TBytes;
      S : String;
    begin
      //AnsiChar内存数组->UnicodeString
      SetLength(Buf , 2);
      Buf[0] := 65;    //A的Ansii码
      Buf[1] := 66;    //B~~
      S := TEncoding.ANSI.GetString(Buf);  //AnsiChar内存数组->UnicodeString
      ShowMessage(S);
     
      //UnicodeString -> AnsiChar内存数组
      SetLength(Buf , 0); //这句是测试时使用,实际使用时,不需要先清除
      Buf := TEncoding.Unicode.GetBytes(S); //UnicodeString -> AnsiChar内存数组
      ShowMessage(IntToStr(Buf[0]));
    end;

    所谓聪明的人用Pascal,Delphi 站在使用者角度可以这么写

    uses SysUtils;

    一、string转为ansistring
    1、直接赋值 (有警告)
    2、ansistring()类型强制转换。(无警告)

    二、ansistring 转为string

    1、直接赋值 (有警告)
    2、string()类型强制转换。(无警告)

    三、string 转为Tbytes

    1、bytes:= bytesof(str) 已转为ansi编码
    2、bytes:= widebytesof(str) UNICODE 编码

    四、ansistring 转为Tbytes

    1、bytes:= bytesof(str) ansi编码
    2、bytes:= widebytesof(string(str)) UNICODE 编码

    五、Tbytes 转为string

    1、 str:=stringof(bytes) Tbytes 为ansi编码
    2、 str:=widestringof(bytes) Tbytes 为unicode编码

    六、PChar转String

    用StrPas函数,StrPas(PChar):AnsiString;


    当然这内部大部分还是还是如下之类!

    Result := TEncoding.UTF8.GetString(TEncoding.UTF8.GetBytes(sTemp));

    这里不得不说说,lazarus/FPC,UTF8作为默认编码,而且强制几次就OK方便很多。

    ————————————————

    部分内容引用
    原文链接:https://blog.csdn.net/u011706768/article/details/119566174「暗夜魔尊」
    原文链接:https://blog.csdn.net/zxm8513/article/details/104728514 「zxm8513」

  • 相关阅读:
    POJ 2891 Strange Way to Express Integers 中国剩余定理 模板 数论
    HDU 6185 Covering 矩阵快速幂 递推
    hdoj2796
    hdoj2795【未完待续】
    hdoj【1006】【未完待续】
    hdoj1007【几何】【未完待续】
    位运算【C++学习(计蒜客)】
    poj1664【DFS】
    退出ACM?
    C4-总结
  • 原文地址:https://www.cnblogs.com/hieroly/p/15553542.html
Copyright © 2020-2023  润新知