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 fdquery遍历输出 json

Delphi中强制idhttp使用http1.1

Delphi 自动把combobox控件的内容里没有的内容加入列表中

Delphi的idhttp报iohandler value is not valid错误的原因

Delphi在字符串中删除指定字符串

Delphi windows 编程[21] - wm_menuselect 消息与 getmenustring 函数

Delphi dbgrid1查询只显示50条记录修改

Delphi 文件分割合并

Delphi xe5 android openurl

Delphi的rtti实现对象的xml持久化

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



打赏

取消

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

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

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

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

评论

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