Delphi-Quellcode:
function FromUTF8 (const S: String): WideString;
...
Diese Funktion hat mir die letzten Jahre gute Dienste als Ersatz f黵 die fehlerhafte UTF8Decode-Funktion in Delphi 2009 geleistet, weil sie zur Interaktion mit einem Produkt genutzt wurde, welches nur die Basic Multilingual Plane (BMP) unterst黷zt. Irgendwie haben es jedoch Leute geschafft, andere Zeichen in die Datenbank zu bekommen und als UTF-8 zu speichern. Die obige Funktion unterst黷zt jedoch UTF-8 nicht und hat deshalb zu Datenverlust gef黨rt. Sie konvertiert lediglich CESU-8 nach UTF-16. L鋝st sich das Ergebnis in UCS-2 darstellen, wird als Nebeneffekt auch UTF-8 nach UCS-2 konvertiert, da sich CESU-8 und UTF-8 da ebensowenig unterscheiden wie UCS-2 und UTF-16. Will man UTF-8 au遝rhalb der BMP nach UTF-16 konvertieren (was bei Delphi normalerweise der Fall ist, da ein WideString UTF-16-Zeichen enth鋖t), produziert die Funktion nur noch Bl鰀sinn.
Da die entsprechend angepasste Funktion auch f黵 andere Nutzer interessant sein k鰊nte, spiel ich mal wieder den Totengr鋌er. Die Funktion konvertiert UTF-8 und CESU-8 nach UTF-16.
Delphi-Quellcode:
function FromUTF8 (const S: String): WideString;
var a,b,c,d: char;
i,j: Integer;
k: Cardinal;
begin
i:=1; j:=1;
SetLength(result,length(S));
while i<=length(S) do
begin
a:=S[i]; Inc(i);
if byte(a)<$80 then
begin
result[j]:=widechar(a);
Inc(j);
continue;
end;
if i>length(S) then break;
b:=S[i]; Inc(i);
if (byte(a)<$E0) or (i>length(S)) then
begin
result[j]:=widechar(((byte(a) and $1F) shl 6) or (byte(b) and $3F));
Inc(j);
continue;
end;
c:=S[i]; Inc(i);
if (byte(a)<$F0) or (i>length(S)) then
begin
result[j]:=widechar(((byte(a) and $F) shl 12) or ((byte(b) and $3F) shl 6) or (byte(c) and $3F));
Inc(j);
continue;
end;
d:=S[i]; Inc(i);
k := ((byte(a) and $7) shl 18) or ((byte(b) and $3F) shl 12) or (byte(c) and $3F shl 6) or (byte(d) and $3F);
result[j]:=widechar((k - $10000) shr 10 and $3FF or $D800);
Inc(j);
result[j]:=widechar(k and $3FF or $DC00);
Inc(j);
end;
SetLength(result,j-1);
end;
Laut deutscher Wikipedia muss die k黵zeste m鰃liche Kodierung gew鋒lt werden. Daher kann man annehmen, dass ein durch 4 Zeichen kodierter Codepunkt nicht in der BMP liegt, sodass man ihn 黚er UTF-16-Surrogates kodieren muss.