问题来源: 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.

posted on 2008-11-23 12:31  万一  阅读(6243)  评论(19编辑  收藏  举报