delphi汉字与多字节编码的转换


本文整理自网络,侵删。

 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.

相关阅读 >>

Delphi post登陆Delphi盒子论坛源码

Delphi indy防止假死

Delphi 监视剪贴板内容

Delphi中使用xmlhttp / xmlhttprequest 避免缓存

Delphi 官方 processmessages 用法代码例子

secsperday:一天共有多少秒

Delphi网络英汉字典代码

Delphi 判断字符串是否是单词

Delphi 刷新桌面函数

Delphi点击网页弹出的alert对话框的确定按钮

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...