• 汉字与多字节编码的转换 回复 "不知道" 的问题


    问题来源: http://www.cnblogs.com/del/archive/2008/11/22/1284923.html#1378410

    Delphi 2009 默认的编码是多字节编码(MBCS), Delphi 这样表示它: TEncoding.Default.

    下面是多字节编码与汉字之间转换的例子:
    unit Unit1;
    
    interface
    
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls;
    
    type
      TForm1 = class(TForm)
        Button1: TButton;
        Button2: TButton;
        Button3: TButton;
        procedure Button1Click(Sender: TObject);
        procedure Button2Click(Sender: TObject);
        procedure Button3Click(Sender: TObject);
      end;
    
    var
      Form1: TForm1;
    
    implementation
    
    {$R *.dfm}
    
    {汉字到多字节编码}
    procedure TForm1.Button1Click(Sender: TObject);
    var
      stream: TStringStream;
      b: Byte;
      s: string;
    begin
      stream := TStringStream.Create('我们', TEncoding.Default);
      s := '';
      for b in stream.Bytes do s := Format('%s%x ', [s,b]);
    
      ShowMessage(s); {CE D2 C3 C7}
      stream.Free;
    end;
    
    {多字节编码到汉字}
    procedure TForm1.Button2Click(Sender: TObject);
    var
      stream: TStringStream;
    begin
      stream := TStringStream.Create;
      stream.Size := 4;
      stream.Bytes[0] := $CE; 
      stream.Bytes[1] := $D2;
      stream.Bytes[2] := $C3;
      stream.Bytes[3] := $C7;
    
      ShowMessage(stream.DataString); {我们}
      stream.Free;
    end;
    
    {把多字节编码的字符串转换到汉字}
    procedure TForm1.Button3Click(Sender: TObject);
    var
      str: AnsiString;
      stream: TStringStream;
      i: Integer;
    begin
      str := 'CED2C3C7';
      stream := TStringStream.Create;
      stream.Size := Length(str) div 2;
    
      for i := 1 to Length(str) do
        if Odd(i) then
          stream.Bytes[i div 2] := StrToIntDef(Concat(#36,str[i],str[i+1]), 0);
    
      ShowMessage(stream.DataString); {我们}
      stream.Free;
    end;
    
    end.
    
  • 相关阅读:
    判断一个点是否在一个不规则多边形内算法
    vue-cli 3.0 安装和创建项目流程
    微信小程序分享朋友圈的实现思路与解决办法
    vue2.0中关于active-class
    Nginx服务启动脚本
    Linux系统优化
    URL检测脚本
    Mysql读写分离php脚本
    Memcahed服务异常监控脚本
    一致性哈希算法PHP测试片段
  • 原文地址:https://www.cnblogs.com/del/p/1339323.html
Copyright © 2020-2023  润新知