首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Delphi 2007解码UTF-8编码西里尔

用Delphi 2007解码UTF-8编码西里尔
EN

Stack Overflow用户
提问于 2013-01-01 03:53:39
回答 2查看 2.9K关注 0票数 4

我在Delphi 2007中工作(不支持Unicode ),我从中检索XML和JSON数据。下面是一些UTF-8编码的数据,我得到了一个URL推荐路径:

ga:referralPath=/add/%D0%9F%D0%B8%D0%B6%D0%B0%D0%BC

当我使用这个解码器解码它时,它正确地生成以下内容:

ga:referralPath=/add/Пижам

我能在Delphi 2007中使用一个函数来执行这个解码吗?

更新--该数据对应于。最终,我想要做的是将它存储在一个SqlServer数据库中(开箱即用--没有修改有关字符集的设置)。然后能够生成/创建一个带有指向此页面的工作链接的html页面(注意:我只处理本例中的url引用路径--显然是为了使一个有效的url链接成为需要的源)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-01 06:54:29

D2007支持Unicode,只是不支持D2009+。D2007中的Unicode是使用WideString和少数现有的RTL支持函数来处理的。

URL包含百分比编码的UTF-8字节八字节字节.只需将这些序列转换为二进制表示,然后使用UTF8Decode()将UTF-8数据解码为WideString。例如:

代码语言:javascript
复制
function HexToBits(C: Char): Byte;
begin
  case C of
    '0'..'9': Result := Byte(Ord(C) - Ord('0'));
    'a'..'f': Result := Byte(10 + (Ord(C) - Ord('a')));
    'A'..'F': Result := Byte(10 + (Ord(C) - Ord('A')));
  else
    raise Exception.Create('Invalid encoding detected');
  end;
end;

var
  sURL: String;
  sWork: UTF8String;
  C: Char;
  B: Byte;
  wDecoded: WideString;
  I: Integer;
begin
  sURL := 'ga:referralPath=/add/%D0%9F%D0%B8%D0%B6%D0%B0%D0%BC';
  sWork := sURL;
  I := 1;
  while I <= Length(sWork) do
  begin
    if sWork[I] = '%' then
    begin
      if (I+2) > Length(sWork) then
        raise Exception.Create('Incomplete encoding detected');
      sWork[I] := Char((HexToBits(sWork[I+1]) shl 4) or HexToBits(sWork[I+2]));
      Delete(sWork, I+1, 2);
    end;
    Inc(I);
  end;
  wDecoded := UTF8Decode(sWork);
  ...
end;
票数 6
EN

Stack Overflow用户

发布于 2013-01-01 09:19:27

您可以使用以下代码,它使用Windows:

代码语言:javascript
复制
function Utf8ToStr(const Source : string) : string;
var
  i, len : integer;
  TmpBuf : array of byte;
begin
  SetLength(Result, 0);
  i := MultiByteToWideChar(CP_UTF8, 0, @Source[1], Length(Source), nil, 0);
  if i = 0 then Exit;
  SetLength(TmpBuf, i * SizeOf(WCHAR));
  Len := MultiByteToWideChar(CP_UTF8, 0, @Source[1], Length(Source), @TmpBuf[0], i);
  if Len = 0 then Exit;

  i := WideCharToMultiByte(CP_ACP, 0, @TmpBuf[0], Len, nil, 0, nil, nil);
  if i = 0 then Exit;

  SetLength(Result, i);
  i := WideCharToMultiByte(CP_ACP, 0, @TmpBuf[0], Len, @Result[1], i, nil, nil);
  SetLength(Result, i);
end;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14107717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档