function EncodeUTF8(
const Source: WideString):
string;
var
Index, SourceLength, CChar: Cardinal;
begin
{ Convert unicode to UTF-8 }
Result := '
';
Index := 0;
SourceLength := Length(Source);
while Index < SourceLength
do
begin
Inc(
Index);
CChar := Cardinal(Source[
Index]);
if CChar <= $7F
then
Result := Result + Source[
Index]
else if CChar > $7FF
then
begin
Result := Result + Char($E0
or (CChar
shr 12));
Result := Result + Char($80
or ((CChar
shr 6)
and $3F));
Result := Result + Char($80
or (CChar
and $3F));
end
else
begin
Result := Result + Char($C0
or (CChar
shr 6));
Result := Result + Char($80
or (CChar
and $3F));
end;
end;
end;
function ToUnicodeString(s: pchar): WideString;
var
pw1 :
array[0..1024]
of WideChar;
nLen1, nLen2, nLen3 : integer;
begin
nLen1 := Length(s);
nLen2 := length(pw1);
nLen3 := MultiByteToWideChar(CP_OEMCP, MB_PRECOMPOSED, s, nLen1, @pw1[0], nLen2);
if nLen3 > 0
then
begin
pw1[nLen3] := chr(0);
// *** We should put chr(0) at the end of string
Result := WideString(pw1);
end else
Result := '
';
end;
function StrToUTF8(s: pchar):
string;
var
w_str : WideString;
begin
w_str := ToUnicodeString(s);
if w_str <> '
'
then
result := EncodeUTF8(w_str)
else
result := '
';
end;