Mega Code Archive

 
Categories / Delphi / Ide Indy
 

ANSI to UTF and back

Title: ANSI to UTF and back Question: Sometimes we need to change our ansi text to utf, i searched the internet for a long time until i found some code. I have no idea who the author is, but whoever it is I think he wouldn't mind to find the code here. Answer: { Function to convert text from UTF8 to ANSI and from ANSI to UTF8 Author unknown } function Utf8ToAnsi(x: string): ansistring; { Function that recieves UTF8 string and converts to ansi string } var i: integer; b1, b2: byte; begin Result := x; i := 1; while i if (ord(Result[i]) and $80) 0 then begin b1 := ord(Result[i]); b2 := ord(Result[i + 1]); if (b1 and $F0) $C0 then Result[i] := #128 else begin Result[i] := Chr((b1 shl 6) or (b2 and $3F)); Delete(Result, i + 1, 1); end; end; inc(i); end; end; function AnsiToUtf8(x: ansistring): string; { Function that recieves ansi string and converts to UTF8 string } var i: integer; b1, b2: byte; begin Result := x; for i := Length(Result) downto 1 do if Result[i] = #127 then begin b1 := $C0 or (ord(Result[i]) shr 6); b2 := $80 or (ord(Result[i]) and $3F); Result[i] := chr(b1); Insert(chr(b2), Result, i + 1); end; end;