关键词:unicodeutf-8编码 gb2312编码 编码转换
本人在实际编程中遇到这个问题,后来终于查到了编码的规则,于是写了一个算法来实现unicode->gb2312的转换,现在将程序代码公布如下:
procedure unicode2gb(const unicodestr:string; var GbStr:String);
var SourceLength:integer;
DoneLength:integer;
AscNo:integer;
Byte1,Byte2,Byte3:integer;
begin
GbStr:='';
if Trim(unicodestr)='' then exit;
SourceLength:=Length(UnicodeStr);
DoneLength:=1;
repeat
AscNo:=ord(UnicodeStr[DoneLength]);
case (AscNo and $E0) of
$E0:begin
Byte1:=(AscNo and $0f) shl 12;
Inc(DoneLength);
if DoneLength>SourceLength then break;
AscNo:=ord(UnicodeStr[DoneLength]);
Byte2:=(AscNo and $3f) shl 6;
Inc(DoneLength);
if DoneLength>SourceLength then break;
AscNo:=ord(UnicodeStr[DoneLength]);
Byte3:=AscNo and $3f;
end;
$C0:begin
Byte1:=(AscNo and $1f) shl 6;
Inc(DoneLength);
if DoneLength>SourceLength then break;
AscNo:=ord(UnicodeStr[DoneLength]);
Byte2:=(AscNo and $3f);
Byte3:=0;
end;
0..$bf:begin
Byte1:=AscNo;
Byte2:=0;
Byte3:=0;
end;
end;//case;
GbStr:=GBStr+widechar(Byte1+Byte2+Byte3);
Inc(DoneLength);
if DoneLength>SourceLength then break;
until DoneLength>=SourceLength;
end;