Delphi перекодировка windows 1251
Подскажите пожалуста,как преобразовать строку из UTF-8 в WIN-1251
← →
umbra © ( 2006-01-26 14:52 ) [1]
← →
Андр ( 2006-01-26 15:14 ) [2]
А в чем возвращается значение после этой функции? в widestring?
← →
umbra © ( 2006-01-26 15:18 ) [3]
в string . и в справке об этом написано
← →
Андр ( 2006-01-26 15:22 ) [4]
Да,Вы правы,написано.
Call Utf8ToAnsi to convert a UTF-8 string to Ansi. S is a string encoded in UTF-8. Utf8ToAnsi returns the corresponding string that uses the Ansi character set.
Только вот такая проблема:
output:=Utf8ToAnsi(Edit1.Text);
Memo2.Lines.Add(output);
не работает.Не могли бы обьяснить почему?
если можно, скажите поподробнее, что значит «не работает». Первое, что приходит в голову — в Edit1.Text находится не UTF8-строка
← →
Андр ( 2006-01-26 17:45 ) [6]
Уже разобрался сам.Дело в том что в кодировке utf8 слово кончается знаком ¶.Я копировал текст из IE ,а он автоматически убирает данный знак.
Все равно спасибо Вам за то что выслушали меня.
Вот рабочий вариант,если кому то надо:
Edit1.Text:=UTF8ToAnsi(Edit2.text);
Delphi перекодировка windows 1251
Имеется проблема: необходимо перекодировать строку в кодировке UTF-8 в Windows-1251 средствами Delphi-4. В Delphi-6 есть функция Utf8ToAnsi, которая и делает все дело, однако в Delphi-4 ее нет. В результате долгих поисков в Интернете нарыл бесплатную библиотеку DIConverters.pas (http://www.zeitungsjunge.de/delphi/converters/index.htm), которая вроде как позволяет конвертировать из UTF-8 в Unicode. Однако умения воспользоваться этой библиотекой не хватает 🙂
Если у кого есть мысли, как выполнить перекодировку UTF-8 —> Unicode —> Windows-1251, please, чиркните примерчик.
← →
dmitry501 © ( 2005-06-08 11:32 ) [1]
Zhachuk © (08.06.05 11:14)
Вот, взял из Audio Tools Library (Freeware) http://jfaul.de/atl
UTF-ANSI
function ConvertFromUTF8(const Source: string): string;
var
Iterator, SourceLength, FChar, NChar: Integer;
begin
< Convert UTF-8 string to ANSI string >
Result := «»;
Iterator := 0;
SourceLength := Length(Source);
while Iterator = $80 then
begin
Inc(Iterator);
if Iterator > SourceLength then break;
FChar := FChar and $3F;
if (FChar and $20) <> 0 then
begin
FChar := FChar and $1F;
NChar := Ord(Source[Iterator]);
if (NChar and $C0) <> $80 then break;
FChar := (FChar shl 6) or (NChar and $3F);
Inc(Iterator);
if Iterator > SourceLength then break;
end;
NChar := Ord(Source[Iterator]);
if (NChar and $C0) <> $80 then break;
Result := Result + WideChar((FChar shl 6) or (NChar and $3F));
end
else
Result := Result + WideChar(FChar);
end;
end;
function DecodeUTF8(const Source: string): WideString;
var
Index, SourceLength, FChar, NChar: Cardinal;
begin
< Convert UTF-8 to unicode >
Result := «»;
Index := 0;
SourceLength := Length(Source);
while Index = $80 then
begin
Inc(Index);
if Index > SourceLength then exit;
FChar := FChar and $3F;
if (FChar and $20) <> 0 then
begin
FChar := FChar and $1F;
NChar := Ord(Source[Index]);
if (NChar and $C0) <> $80 then exit;
FChar := (FChar shl 6) or (NChar and $3F);
Inc(Index);
if Index > SourceLength then exit;
end;
NChar := Ord(Source[Index]);
if (NChar and $C0) <> $80 then exit;
Result := Result + WideChar((FChar shl 6) or (NChar and $3F));
end
else
Result := Result + WideChar(FChar);
end;
end;
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 $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;
Перекодирование Utf-8 в windows-1251
Delphi , Синтаксис , Кодировки
Перекодирование Utf-8 в windows-1251
Данная функция будет полезна в случае если, по тем или иным причинам, нельзя применять, стандартную функцию UTF8Decode, например если программа будет запускаться под wine в UNIX-подобных системах.
Utf2WinTable : array [0..65, 0..1] of string = (
(#208#144,#192), (#208#145,#193), (#208#146,#194),
(#208#147,#195), (#208#148,#196), (#208#149,#197),
(#208#129,#168), (#208#150,#198), (#208#151,#199),
(#208#152,#200), (#208#153,#201), (#208#154,#202),
(#208#155,#203), (#208#156,#204), (#208#157,#205),
(#208#158,#206), (#208#159,#207), (#208#160,#208),
(#208#161,#209), (#208#162,#210), (#208#163,#211),
(#208#164,#212), (#208#165,#213), (#208#166,#214),
(#208#167,#215), (#208#168,#216), (#208#169,#217),
(#208#170,#218), (#208#171,#219), (#208#172,#220),
(#208#173,#221), (#208#174,#222), (#208#175,#223),
(#208#176,#224), (#208#177,#225), (#208#178,#226),
(#208#179,#227), (#208#180,#228), (#208#181,#229),
(#209#145,#184), (#208#182,#230), (#208#183,#231),
(#208#184,#232), (#208#185,#233), (#208#186,#234),
(#208#187,#235), (#208#188,#236), (#208#189,#237),
(#208#190,#238), (#208#191,#239), (#209#128,#240),
(#209#129,#241), (#209#130,#242), (#209#131,#243),
(#209#132,#244), (#209#133,#245), (#209#134,#246),
(#209#135,#247), (#209#136,#248), (#209#137,#249),
(#209#138,#250), (#209#139,#251), (#209#140,#252),
(#209#141,#253), (#209#142,#254), (#209#143,#255) );
function Utf8ToWin(s : string) : string;
var i : integer;
res :string;
begin
res:=s;
for I := 0 to 65 do
if pos(Utf2WinTable[i,0],res)>0
then res := StringReplace(res, Utf2WinTable[i,0], Utf2WinTable[i,1], [rfReplaceAll]);
Статья Перекодирование Utf-8 в windows-1251 раздела Синтаксис Кодировки может быть полезна для разработчиков на Delphi и FreePascal.
Перекодировка из UTF8 в Win-1251
Доброго времени суток!!
Вопрос — перекодировка из UTF8 в Win-1251
Никогда не сталкивался
Подскажите ход мыслей
Добавлено через 14 часов 31 минуту
Прошу переименовать тему.
Вопрос такой: Unicode -> Win 1251
На вопрос:
UTF8 в Win-1251 ответ найден, вернее ответ на вопросы перекодировки всего во все, окромя Unicode
Сдается мне, что вопрос прост, только теории знания у меня нет вот и не понимаю, как его, Unicode брать и пользовать
Win-1251 в UTF8 в текстовый документ
Есть файл в win-1251, нужно загрузить его в memo/stringlist в кодировке UTF8 var s,sl.
Перекодировка строки win-1251 в кодировку utf-8
Помогите пожалуйста! есть проблема перекодировки строки win-1251 в кодировку utf-8. Может есть.
Не получается перекодировать UTF8 в win-1251
во первых никак его не могу перекодировать в win-1251 а во вторых как открыть в Stream Reader.
Перекодировка содержимого текстового файла в Win-1251 и запись результата в новый файл с именем компьютера
Добрый день, подскажите пожалуйста. стоит задача написать bat, который будет собирать информацию.
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Перекодировка Win1241 в UTF8
Перекодировка Win1241 в UTF8. Помогите строчкой кода.
Перекодировка строки в Windows-1251
Формирую QR-код через dll которую 1С используют в типовых решениях (БГУ и проч). Загоняю строку в.
Перекодировка из КОИ-8 в Windows 1251
Разработать программу перекодировки текстовых файлов из кодового набора КОИ-8 в кодовый набор.
Перекодировка с windows-1251 в utf-8
как можно написать процедуру на pl/sql, чтобы перекодировал с windows-1251 в utf-8 ?
Convert text from UTF-8 to Windows 1251
I try to convert text in utf8 to windows1251.
This is source text Ñàíêò-Ïåòåðáóðã This is targer Санкт-Петербург
I tested a lot of functions: Utf8ToAnsi, UTF8ToString, Utf8Encode and other but didn’t get true result.
2 Answers 2
Let’s try to guess what you are asking. Look at the first five characters:
If we assume that they are in fact from 8 bit Windows code page 1252 then in hex they are encoded like this:
Now, those five bytes when interpreted as 8 bit Windows code page 1251 are:
So it seems that there is no UTF-8 involved here. You are simply misinterpreting text as being from code page 1252 when in fact it is from 1251.
I tested a lot of functions: Utf8ToAnsi, UTF8ToString, Utf8Encode and other but didn’t get true result.
As a more general point, when you find yourself calling functions at random, usually that means that you don’t yet fully understand the problem. It’s a useful skill to be able to recognise that feeling, and know that it is time to step back and attempt to gain a deeper understanding.
There’s not much point in anybody explaining how to convert from UTF-8 to 1251 since that’s not what you need to do. I’m not going to try to show you any code to solve your problem because I don’t know:
- Where the data comes from, or
- What form you need the data to be subsequently transformed into.
Most likely you have read these bytes into an AnsiString with code page 1252. But at this point I judge the guesswork to be a step too far. If you add some clarification to your question then we might be able to add more detail.
I try to convert text in utf8 to windows1251.
Since you are using Delphi 2009+, the easiest solution is to use the UT8String and AnsiString(N) types and let the RTL handle the conversion for you (unless you are compiling for mobile platforms, in which case UTF8String and AnsiString(N) are not available without installing a third party compiler patch):
Alternatively, you can use the RTL’s UnicodeFromLocaleChars() and LocaleCharsFromUnicode() functions:
Or you can use the Win32 MultiByteToWideChar() and WideCharToMultiByte() functions directly (or a third-party Unicode library, such as iconv or ICU):
This is source text Ñàíêò-Ïåòåðáóðã This is targer Санкт-Петербург
Ñàíêò-Ïåòåðáóðã is not the UTF-8 encoded form of Санкт-Петербург , the correct UTF-8 encoded form would be Санкт-Петербург instead. So, as other people have pointed out, your data is not actually encoded in UTF-8 to begin with.
I tested a lot of functions: Utf8ToAnsi, UTF8ToString, Utf8Encode and other but didn’t get true result.
Utf8ToAnsi() does not allow you to specify the target charset. In Delphi 2009+, it decodes a UTF-8 string to a UTF-16 UnicodeString . In pre-2009 versions, it decodes to an AnsiString that is encoded using the OS default Ansi codepage, whatever that happens to be.
UTF8ToString() decodes a UTF-8 string to a UTF-16 UnicodeString .
Utf8Encode() encodes a UTF-16 WideString / UnicodeString to UTF-8.