我在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链接成为需要的源)。
发布于 2013-01-01 06:54:29
D2007支持Unicode,只是不支持D2009+。D2007中的Unicode是使用WideString和少数现有的RTL支持函数来处理的。
URL包含百分比编码的UTF-8字节八字节字节.只需将这些序列转换为二进制表示,然后使用UTF8Decode()将UTF-8数据解码为WideString。例如:
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;发布于 2013-01-01 09:19:27
您可以使用以下代码,它使用Windows:
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;https://stackoverflow.com/questions/14107717
复制相似问题