日志

查看日志|返回日志列表

如何将unicode(utf-8)编码转换为gb2312编码

标签如何  unicode  2008-12-12 16:36

本人在实际编程中遇到这个问题,后来终于查到了编码的规则,于是写了一个算法来实现unicode->gb2312的转换,现在将程序代码公布如下:  

{
unicode->gb2312
Aurhor:tommcat
Homepage:http://www.tommstudio.com
转载请保留完整信息
}

procedure unicode2gb(const unicodestr:stringvar 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;
分享 162 次阅读 | 0 个评论
上一篇: 查找所有网络计算机
下一篇: 使用 IStream

留下脚印

评论


相关资源下载