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 调用js脚本

学习使用Delphi for android 调用java类库

Delphi 把流中的字符串转换为 utf 格式

Delphi 创建新的messagebox窗口前,先关掉之前已经创建好的

Delphi 枚举类型和integer整型之间的互换

Delphi httpclient async异步获取网页代码

Delphi 使用泛型的 tarray 从动态数组中查找指定元素

Delphi 遍历某字段并插入到combobox

Delphi 为 service application 添加描述文本的方法

Delphi中强制idhttp使用http1.1

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



打赏

取消

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

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

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

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

评论

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