A literal translation would look like this:
function UTF8FromUTF16(const abytUTF16: TBytes): TBytes;
var
lngByteNum: LongInt;
abytUTF8: TBytes;
lngCharCount: LongInt;
begin
Result := nil;
lngCharCount := Length(abytUTF16) div 2;
lngByteNum := WideCharToMultiByte(CP_UTF8, 0, PWideChar(abytUTF16), lngCharCount, nil, 0, nil, nil);
if lngByteNum > 0 then
begin
SetLength(abytUTF8, lngByteNum);
lngByteNum := WideCharToMultiByte(CP_UTF8, 0, PWideChar(abytUTF16), lngCharCount, PAnsiChar(abytUTF8), lngByteNum, nil, nil);
Result := abytUTF8;
Exit;
end;
if GetLastError <> 0 then
MessageBox(0, ' Conversion failed ', '', MB_OK);
end;
In Delphi 2009+, there is a much simplier approach:
function UTF8FromUTF16(const abytUTF16: TBytes): TBytes;
begin
Result := TEncoding.Convert(TEncoding.Unicode, TEncoding.UTF8, abytUTF16);
end;
Even easier, if you work with strings instead of bytes, then you can simply assign a WideString
or a UnicodeString
(both of which are UTF-16 encoded) to a UTF8String
and let the RTL handle the conversion for you.