<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Серый форум &mdash; VBScript: конвертация текста из кодировки в кодировку]]></title>
		<link>http://forum.script-coding.com/viewtopic.php?id=1179</link>
		<atom:link href="http://forum.script-coding.com/extern.php?action=feed&amp;tid=1179&amp;type=rss" rel="self" type="application/rss+xml" />
		<description><![CDATA[Недавние сообщения в теме «VBScript: конвертация текста из кодировки в кодировку».]]></description>
		<lastBuildDate>Fri, 18 Sep 2020 03:46:56 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[Re: VBScript: конвертация текста из кодировки в кодировку]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=142185#p142185</link>
			<description><![CDATA[<p>Да. Ты прав. Боевые функции для программистов, Универсальные для домохозяек, которым не надо исполнять код здесь и сейчас без перекодирования с временными файлами.<br />Вообщем - глубоко передаланный твой код декодирования и мой личный код кодирования через MSHTA-JS.<br />Принимает данные из буфера обмена и в качестве входного параметра. Обратно, в качестве ответа, ничего не возвращает <img src="//forum.script-coding.com/img/smilies/smile.png" width="15" height="15" /><br />Временные файлы не создаются.</p><p>Encode URI</p><p>&nbsp; &nbsp; Option Explicit<br />&nbsp; &nbsp; Const WshRunning = 0,WshFailed = 1:Dim cmd,text,i,objShell<br />&nbsp; &nbsp; Dim strCmd, objWnd, objParent, strSignature, output, wowError, exec, arr, j, temp<br />&nbsp; &nbsp; wowError=False<br />&nbsp; &nbsp; Set objShell = WScript.CreateObject(&quot;WScript.Shell&quot;)<br />&nbsp; &nbsp; Sub RunCScriptHidden()<br />&nbsp; &nbsp; &nbsp; &nbsp; strSignature = Left(CreateObject(&quot;Scriptlet.TypeLib&quot;).Guid, 38)<br />&nbsp; &nbsp; &nbsp; &nbsp; GetObject(&quot;new:{C08AFD90-F2A1-11D1-8455-00A0C91F3880}&quot;).putProperty strSignature, Me<br />&nbsp; &nbsp; &nbsp; &nbsp; objShell.Run (&quot;&quot;&quot;&quot; &amp; Replace(LCase(WScript.FullName), &quot;wscript&quot;, &quot;cscript&quot;) &amp; &quot;&quot;&quot; //nologo &quot;&quot;&quot; &amp; WScript.ScriptFullName &amp; &quot;&quot;&quot; &quot;&quot;/signature:&quot; &amp; strSignature &amp; &quot;&quot;&quot;&quot;), 0, True<br />&nbsp; &nbsp; End Sub<br />&nbsp; &nbsp; Sub WshShellExecCmd()<br />&nbsp; &nbsp; &nbsp; &nbsp; For Each objWnd In CreateObject(&quot;Shell.Application&quot;).Windows<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; If IsObject(objWnd.getProperty(WScript.Arguments.Named(&quot;signature&quot;))) Then Exit For<br />&nbsp; &nbsp; &nbsp; &nbsp; Next<br />&nbsp; &nbsp; &nbsp; &nbsp; Set objParent = objWnd.getProperty(WScript.Arguments.Named(&quot;signature&quot;))<br />&nbsp; &nbsp; &nbsp; &nbsp; objWnd.Quit<br />&nbsp; &nbsp; &nbsp; &nbsp; Set exec = CreateObject(&quot;WScript.Shell&quot;).Exec(objParent.strCmd)<br />&nbsp; &nbsp; 	While exec.Status = WshRunning<br />&nbsp; &nbsp; 		WScript.Sleep 50<br />&nbsp; &nbsp; 	Wend<br />&nbsp; &nbsp; 	Dim err<br />&nbsp; &nbsp; 	If exec.ExitCode = WshFailed Then<br />&nbsp; &nbsp; 		err = exec.StdErr.ReadAll<br />&nbsp; &nbsp; 	Else<br />&nbsp; &nbsp; 		output = Split(exec.StdOut.ReadAll,Chr(10))<br />&nbsp; &nbsp; 	End If<br />&nbsp; &nbsp; 	If err=&quot;&quot; Then<br />&nbsp; &nbsp; 		objParent.text = output(UBound(output)-1) &#039;array of results, you can: output(0) Join(output) - Usually needed is the last<br />&nbsp; &nbsp; 	Else<br />&nbsp; &nbsp; 		objParent.wowError = err<br />&nbsp; &nbsp; 	End If<br />&nbsp; &nbsp; WScript.Quit<br />&nbsp; &nbsp; End Sub<br />&nbsp; &nbsp; text=CreateObject(&quot;HTMLFile&quot;).parentWindow.clipboardData.GetData(&quot;text&quot;)	<br />&nbsp; &nbsp; text=Replace(text,&quot;\&quot;,&quot;\\&quot;)<br />&nbsp; &nbsp; text=Replace(text,&quot;&#039;&quot;,&quot;\%27&quot;)<br />&nbsp; &nbsp; text=Replace(text,Chr(34),&quot;%22&quot;)<br />&nbsp; &nbsp; text=Replace(text,&quot;^&quot;,&quot;%5E&quot;)<br />&nbsp; &nbsp; <br />&nbsp; &nbsp; cmd=&quot;for /f &quot;&quot;usebackq&quot;&quot; %i in &quot; &amp; _<br />&nbsp; &nbsp; &quot;(`mshta &quot;&quot;javascript:Code(close(new ActiveXObject(&#039;Scripting.FileSystemObject&#039;).GetStandardStream(1).Write(&quot; &amp; _<br />&nbsp; &nbsp; &quot;encodeURIComponent(&#039;&quot; &amp; text &amp; &quot;&#039;)&quot; &amp; _<br />&nbsp; &nbsp; &quot;)));&quot;&quot;`) do set e=%i&amp;set e=!e:&#039;=%27!&amp;set e=!e:(=%28!&amp;set e=!e:)=%29!&amp;echo !e!&quot;:strCmd = &quot;%comspec% /v /c &quot; &amp; cmd<br />&nbsp; &nbsp; If WScript.Arguments.Named.Exists(&quot;signature&quot;) Then WshShellExecCmd<br />&nbsp; &nbsp; RunCScriptHidden<br />&nbsp; &nbsp; If wowError=False Then<br />&nbsp; &nbsp; 	text=text<br />&nbsp; &nbsp; 	For j = 0 To 13<br />&nbsp; &nbsp; 		text=Replace(text,Chr(j),&quot;&quot;)			<br />&nbsp; &nbsp; 	Next<br />&nbsp; &nbsp; 	objShell.popup(text)<br />&nbsp; &nbsp; Else<br />&nbsp; &nbsp; 	objShell.popup(&quot;Error=&quot; &amp; wowError)<br />&nbsp; &nbsp; End If</p><p>Encode with IE</p><p>&nbsp; &nbsp; Option Explicit<br />&nbsp; &nbsp; Dim text,ws,F,FSO,path,name,j<br />&nbsp; &nbsp; text=CreateObject(&quot;HTMLFile&quot;).parentWindow.clipboardData.GetData(&quot;text&quot;)	<br />&nbsp; &nbsp; Dim oIE: Set oIE = CreateObject(&quot;InternetExplorer.application&quot;)<br />&nbsp; &nbsp; With oIE<br />&nbsp; &nbsp; 	.Visible = False<br />&nbsp; &nbsp; 	.Navigate (&quot;&quot;)<br />&nbsp; &nbsp; 	.Offline = True<br />&nbsp; &nbsp; End With<br />&nbsp; &nbsp; Do Until oIE.ReadyState = 4<br />&nbsp; &nbsp; 	wscript.sleep 100<br />&nbsp; &nbsp; Loop<br />&nbsp; &nbsp; For j = 0 To 13 &#039;text=Replace(text,Chr(13),&quot;&quot;)<br />&nbsp; &nbsp; 	text=Replace(text,Chr(j),&quot;&quot;)			<br />&nbsp; &nbsp; Next<br />&nbsp; &nbsp; text=Replace(text,&quot;\&quot;,&quot;\\&quot;)<br />&nbsp; &nbsp; text=Replace(text,Chr(34),&quot;%22&quot;)<br />&nbsp; &nbsp; text=Replace(text,&quot;(&quot;,&quot;%28&quot;)<br />&nbsp; &nbsp; text=Replace(text,&quot;)&quot;,&quot;%29&quot;)<br />&nbsp; &nbsp; oIE.Document.parentWindow.execScript(&quot;var ultimateAnswer = function(){return encodeURIComponent(&quot;&quot;&quot; &amp; text &amp; &quot;&quot;&quot;);};ultimateAnswer()&quot;) &#039;Get Return value<br />&nbsp; &nbsp; text = oIE.Document.parentWindow.ultimateAnswer()<br />&nbsp; &nbsp; &#039;text=Replace(text,&quot;[&quot;,&quot;%5B&quot;)<br />&nbsp; &nbsp; &#039;text=Replace(text,&quot;]&quot;,&quot;%5D&quot;)<br />&nbsp; &nbsp; &#039;text=Replace(text,&quot; &quot;,&quot;%20&quot;)<br />&nbsp; &nbsp; &#039;text=Replace(text,&quot;+&quot;,&quot;%2B&quot;)<br />&nbsp; &nbsp; text=Replace(text,&quot;&#039;&quot;,&quot;`%27&quot;)<br />&nbsp; &nbsp; text=Replace(text,&quot;%2522&quot;,&quot;`%22&quot;)<br />&nbsp; &nbsp; text=Replace(text,&quot;%2528&quot;,&quot;%28&quot;)<br />&nbsp; &nbsp; text=Replace(text,&quot;%2529&quot;,&quot;%29&quot;)<br />&nbsp; &nbsp; text= Chr(34) &amp; text &amp; Chr(34)<br />&nbsp; &nbsp; objShell.popup(text)<br />	oIE.Quit</p><p>Decode URI</p><p>	Option Explicit<br />	Dim Kod<br />	If WScript.Arguments.Count()=0 Then <br />	&nbsp; &nbsp; Kod=CreateObject(&quot;HTMLFile&quot;).parentWindow.clipboardData.GetData(&quot;text&quot;) <br />	Else<br />	&nbsp; &nbsp; Kod=WScript.Arguments(0)<br />	End if<br />	if IsNull(Kod) Then <br />	&nbsp; &nbsp; WScript.Echo &quot;No data to execute..&quot;<br />	Else<br />	&nbsp; &nbsp; Dim chunk,Recoded,k1,k2,k3,i:i=0:Dim arr:arr=Split(Kod,&quot;%&quot;)<br />	&nbsp; &nbsp; Do While i &lt;= UBound(arr)<br />	&nbsp; &nbsp; &nbsp; &nbsp; if i&lt;&gt;0 Then<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; chunk = Left(arr(i),2)&nbsp; &nbsp; &nbsp; <br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; If &quot;&amp;H&quot;&amp;Left(chunk,2)&gt;=128 then<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr(i)=&quot;&quot;:i=i+1:chunk = chunk &amp; Left(arr(i),2)<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; If &quot;&amp;H&quot;&amp;Left(chunk,2)&lt;224 then <br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; k1=Cint(&quot;&amp;H&quot;&amp;Left(chunk,2)) mod 32<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; k2 = Cint(&quot;&amp;H&quot;&amp;Mid(chunk,3,2)) mod 64<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Recoded=ChrW( k2 + k1 * 64 )<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Else<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr(i)=&quot;&quot;:i=i+1:chunk = chunk &amp; Left(arr(i),4)<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; k1=Cint(&quot;&amp;H&quot;&amp;Left(chunk,2)) mod 16<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; k2 = Cint(&quot;&amp;H&quot;&amp;Mid(chunk,3,2)) mod 32<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; k3 = Cint(&quot;&amp;H&quot;&amp;Mid(chunk,5,2)) mod 64<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Recoded=ChrW( k3 + ( k2 + k1 * 64 ) * 64 )<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; End if<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Else Recoded=Chr(&quot;&amp;H&quot;&amp;chunk)<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; End If<br />	&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr(i)=Recoded &amp; Mid(arr(i),3)<br />	&nbsp; &nbsp; &nbsp; &nbsp; end if:i=i+1<br />	&nbsp; &nbsp; loop<br />	&nbsp; &nbsp; Kod=Join(arr,&quot;&quot;):WScript.Echo Kod<br />	End if</p>]]></description>
			<author><![CDATA[null@example.com (yandibaev)]]></author>
			<pubDate>Fri, 18 Sep 2020 03:46:56 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=142185#p142185</guid>
		</item>
		<item>
			<title><![CDATA[Re: VBScript: конвертация текста из кодировки в кодировку]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=42972#p42972</link>
			<description><![CDATA[<p>Вот примитивная конвертация:<br /></p><div class="codebox"><pre><code>function convert_cyr_string(str,src,dst)
   src = lcase(src)
   dst = lcase(dst)
   dim Fsrc, Fdst, ArrFdos, ArrFwin, ArrFutf, d, Simv, n
   ArrFdos = split(&quot;128;129;130;131;132;133;134;135;136;137;138;139;140;141;142;143;144;145;146;147;148;149;150;151;152;153;154;155;156;157;158;159;160;161;162;163;164;165;166;167;168;169;170;171;172;173;174;175;224;225;226;227;228;229;230;231;232;233;234;235;236;237;238;239;240;241&quot;,&quot;;&quot;)
   ArrFwin = split(&quot;192;193;194;195;196;197;198;199;200;201;202;203;204;205;206;207;208;209;210;211;212;213;214;215;216;217;218;219;220;221;222;223;224;225;226;227;228;229;230;231;232;233;234;235;236;237;238;239;240;241;242;243;244;245;246;247;248;249;250;251;252;253;254;255;168;184&quot;,&quot;;&quot;)
   ArrFutf = split(&quot;208:144;208:145;208:146;208:147;208:148;208:149;208:150;208:151;208:152;208:153;208:154;208:155;208:156;208:157;208:158;208:159;208:160;208:161;208:162;208:163;208:164;208:165;208:166;208:167;208:168;208:169;208:170;208:171;208:172;208:173;208:174;208:175;208:176;208:177;208:178;208:179;208:180;208:181;208:182;208:183;208:184;208:185;208:186;208:187;208:188;208:189;208:190;208:191;209:128;209:129;209:130;209:131;209:132;209:133;209:134;209:135;209:136;209:137;209:138;209:139;209:140;209:141;209:142;209:143;208:129;209:145&quot;,&quot;;&quot;)
   if (src = &quot;w&quot; and dst = &quot;w&quot;) or (src = &quot;d&quot; and dst = &quot;d&quot;) or (src = &quot;u&quot; and dst = &quot;u&quot;) then
      convert_cyr_string = str
      exit function
   end if
   if src = &quot;w&quot; then
         Fsrc = ArrFwin
      elseif lcase(src) = &quot;d&quot; then
         Fsrc = ArrFdos
      elseif lcase(src) = &quot;u&quot; then
         Fsrc = ArrFutf
      else
         convert_cyr_string = &quot;Err: The variable src isn&#039;t true&quot;
         exit function
   end if
   if dst = &quot;w&quot; then
         Fdst = ArrFwin
      elseif dst = &quot;d&quot; then
         Fdst = ArrFdos
      elseif dst = &quot;u&quot; then
         Fdst = ArrFutf
      else
         convert_cyr_string = &quot;Err: The variable dst isn&#039;t true&quot;
         exit function
   end if
   Set d = CreateObject(&quot;Scripting.Dictionary&quot;) 
   for n=0 to ubound(Fsrc)
         d.Add Fsrc(n), Fdst(n)
   next
   if (src = &quot;w&quot; and dst = &quot;d&quot;) or (src = &quot;d&quot; and dst = &quot;w&quot;) then
      for n = 1 to len(str)
         if d.item(cStr(asc(mid(str,n,1)))) &lt;&gt; &quot;&quot; then
            Simv = Simv &amp; chr(d.item(cStr(asc(mid(str,n,1)))))
         else
            Simv = Simv &amp; mid(str,n,1)
         end if
      next
   elseif src = &quot;u&quot; then
      for n = 1 to len(str)
         if asc(mid(str,n,1)) = 208 or asc(mid(str,n,1)) = 209 then
            Simv = Simv &amp; chr(d.Item(cStr(asc(left(mid(str,n,2),1)) &amp; &quot;:&quot; &amp; asc(right(mid(str,n,2),1)))))
            n = n + 1
         else
            Simv = Simv &amp; mid(str,n,1)
         end if
      next
   elseif dst = &quot;u&quot; then
      for n = 1 to len(str)
         if d.item(cStr(asc(mid(str,n,1)))) &lt;&gt; &quot;&quot; Then
            Simv = Simv &amp; chr(left(d.item(cStr(asc(mid(str,n,1)))),3)) &amp; chr(right(d.item(cStr(asc(mid(str,n,1)))),3)) 
         else
            Simv = Simv &amp; mid(str,n,1)
         end if
      next
   end if
   set d = Nothing
   convert_cyr_string = Simv
end function</code></pre></div><p>Немного усовершенствовал с последнего раза. Функция принимает строку в кодировке src и возвращает в кодировке dst.<br />src и&nbsp; dst могу принимать следующие значения: &quot;d&quot;, &quot;w&quot;, &quot;u&quot; - 866, 1251 и UTF соответственно.</p>]]></description>
			<author><![CDATA[null@example.com (Wiliam)]]></author>
			<pubDate>Fri, 24 Dec 2010 09:05:04 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=42972#p42972</guid>
		</item>
		<item>
			<title><![CDATA[Re: VBScript: конвертация текста из кодировки в кодировку]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=40603#p40603</link>
			<description><![CDATA[<div class="quotebox"><cite>fps пишет:</cite><blockquote><p>SourceCharset и DestCharset в нем тоже перепутаны</p></blockquote></div><p>Описанная путаница возникает не здесь , а гораздо раньше - в названии функции <strong>StrConv</strong>. Дело в том, что это не функция конвертации по своему основному смыслу, конвертирование там есть одно вспомогательное, а это функция рассмотрения одной кодиовки КАК другой (ЧЕРЕЗ призму другой), т.е. назвать ее следовало бы сделать <strong>StrViewAs</strong>. И написать примерно следующее :</p><div class="codebox"><pre><code>&#039; Серия преобразований strText как SourceCharset, рассмотрение полученного как TargetCharset
Public Function StrViewAs(ByVal strText, ByVal CharsetList) &#039;
&#039; http://forum.script-coding.com/viewtopic.php?id=997
&#039; http://p10903.clients.m-10.ru/viewtopic.php?pid=30379
&#039; HKEY_CLASSES_ROOT\Mime\Database - разрешенные для использования кодировки
&#039; HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage\  ACP=1251 - текущая кодировка Windows, OEMCP=866 - текущая кодировка DOS
&#039;
&#039; Внутренне каждый символ strText при этом представлен в UTF16-LE (Unicode Windows) двумя байтами, как и везде в VB строках .
&#039; CharsetList -&gt; &quot;[SourceCharset]/[TargetCharset]...&quot; Т.е. это список пар,разделенных / кодировок преобразования/рассмотрения
&#039;                 SourceCharset - кодировка в которой должна интерпретироваться исходная строка
&#039;                 TargetCharset - кодировка через призму которой должна смотреться преобразованная исходная строка, после чего преобразованная
&#039;                                 вновь дожна интерпретироваться/рассматриваться следующей из списка парой [SourceCharset]/[TargetCharset]
&#039;                 Если какая-то кодировка опущена , то считается - системная по умолчанию (&quot;Windows-1251&quot; для нас).
&#039;                 OEM в имени кодировки означает использование кодировки по умолчанию для DOS (&quot;cp866&quot; для нас)
&#039; Примеры :
&#039;  StrViewAs(&quot;Ю&quot;,&quot;koi8-r/&quot;), StrViewAs(&quot;Ю&quot;,&quot;windows-1251/koi8-r/koi8-r/windows-1251&quot;),StrViewAs(&quot;Юра&quot;,&quot;koi8-r///koi8-r&quot;)
Const adTypeText = 2, adModeReadWrite = 3
Dim objStream, i, WshShell, ACP, OEMCP

Set objStream = CreateObject(&quot;ADODB.Stream&quot;)
Set WshShell = CreateObject(&quot;WScript.Shell&quot;)
ACP = &quot;Windows-&quot; &amp; WshShell.RegRead(&quot;HKLM\SYSTEM\CurrentControlSet\Control\Nls\CodePage\ACP&quot;)
OEMCP = &quot;cp&quot; &amp; WshShell.RegRead(&quot;HKLM\SYSTEM\CurrentControlSet\Control\Nls\CodePage\OEMCP&quot;)

CharsetList = Split(Trim(CharsetList), &quot;/&quot;)
With objStream
 .Type = adTypeText: .Mode = adModeReadWrite: .Open
 
 For i = 0 To UBound(CharsetList) Step 2
  If CharsetList(i) = &quot;&quot; Then CharsetList(i) = ACP
  If UCase(CharsetList(i)) = &quot;OEM&quot; Then CharsetList(i) = OEMCP
  .Position = 0: .Charset = CharsetList(i)     &#039; strText будем заносить в поток под SourceCharset
  .WriteText strText                           &#039; strText Unicode -:-&gt; SourceCharset
  If CharsetList(i + 1) = &quot;&quot; Then CharsetList(i + 1) = ACP
  If UCase(CharsetList(i + 1)) = &quot;OEM&quot; Then CharsetList(i + 1) = OEMCP
  .Position = 0: .Charset = CharsetList(i + 1) &#039; рассматриваем SourceCharset как TargetCharset
  strText = .ReadText                          &#039; TargetCharset  -:-&gt; Unicode
 Next

End With
StrViewAs = strText
Set objStream = Nothing
End Function &#039; StrViewAs --&gt;&gt;</code></pre></div><p><strong>В связи с чем хотелось бы уточнить, т.к. сомневаюсь правильно ли сделал нахождение имен кодировок по умолчанию для Windows и для DOS : ACP и OEMCP. Плз. подскажите - как их правильно сформировать можно ?</strong></p><div class="quotebox"><cite>RootAdmin пишет:</cite><blockquote><p>Имхо, использовать объекты - не то...<br />Лучше самостоятельно.<br />Вот, пожалуйста, &quot;боевые функции&quot;</p></blockquote></div><p>Я вот тоже пробовал писать такие, только желание было досконально разобраться и все учесть - так все учесть не получилось, поэтому решил лучше черз потоки использовать.</p>]]></description>
			<author><![CDATA[null@example.com (kefi)]]></author>
			<pubDate>Tue, 19 Oct 2010 21:20:42 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=40603#p40603</guid>
		</item>
		<item>
			<title><![CDATA[Re: VBScript: конвертация текста из кодировки в кодировку]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=30379#p30379</link>
			<description><![CDATA[<p>Абсолютно согласен, но в практике чего только не приходилось встречать. И по три-четыре преобразования в почтовых клиентах, когда &quot;URL-Quoted printable&quot; завернуто в base-64 и обозвано UTF-8?B?<br />Опять же, когда сам попробуешь - приходит опыт, когда начинаешь понимать что ж именно отдаешь системе для преобразования, как именно оно выглядит на уровне байт.<br />Приходилось видеть как система тупо (вместо преобразования кодировки) дописывает в начало строки два байта BOM и возвращает. Хотя это было давно, лет 5 назад.</p>]]></description>
			<author><![CDATA[null@example.com (RootAdmin)]]></author>
			<pubDate>Wed, 11 Nov 2009 09:07:27 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=30379#p30379</guid>
		</item>
		<item>
			<title><![CDATA[Re: VBScript: конвертация текста из кодировки в кодировку]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=30378#p30378</link>
			<description><![CDATA[<p><strong>RootAdmin</strong>, видите ли в чём дело: Ваш метод работает для одной выбранной пары кодировок (и кодовых страниц), а тут всё ручное преобразование отдаётся на откуп ОС.</p><p>Хотя, не спорю, в ряде случаев приходится пользоваться именно подобным «ручным» способом.</p>]]></description>
			<author><![CDATA[null@example.com (alexii)]]></author>
			<pubDate>Wed, 11 Nov 2009 08:50:52 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=30378#p30378</guid>
		</item>
		<item>
			<title><![CDATA[Re: VBScript: конвертация текста из кодировки в кодировку]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=30377#p30377</link>
			<description><![CDATA[<p>Имхо, использовать объекты - не то...<br />Лучше самостоятельно.<br />Вот, пожалуйста, &quot;боевые функции&quot;<br /></p><div class="codebox"><pre><code>Set WshShell = Wscript.CreateObject(&quot;Wscript.Shell&quot;)

Kod=&quot;%D0%B2%D1%8B%D0%B3%D1%80%D1%83%D0%B7%D0%BA%D0%B0%5F%30&quot;
Kod=Replace(Kod,&quot;%&quot;,&quot;&quot;)
WshShell.popup Kod&amp;&quot; длина &quot;&amp;Len(kod)
        &#039;Перекодирую. Первый ДВА байта строки - код кодировки в H записи, следующие - код символа.
        While len(kod)&gt;0
            &#039;Проверим ПЕРВЫЙ символ, определим сколько битное кодирование
            If &quot;&amp;H&quot;&amp;Left(kod,2)&gt;=128 then 
            &#039;Больше чем байт
                If &quot;&amp;H&quot;&amp;Left(kod,2)&lt;224 then 
                &#039;Два байта
                    k1=Cint(&quot;&amp;H&quot;&amp;Left(kod,2)) mod 32
                    k2 = Cint(&quot;&amp;H&quot;&amp;Mid(kod,3,2)) mod 64
                    NameKoder=NameKoder&amp;ChrW( k2 + k1 * 64 )
                    Kod=Right(kod,Len(kod)-4)
                Else
                &#039;Три байта
                    k1=Cint(&quot;&amp;H&quot;&amp;Left(kod,2)) mod 16
                    k2 = Cint(&quot;&amp;H&quot;&amp;Mid(kod,3,2)) mod 32
                    k2 = Cint(&quot;&amp;H&quot;&amp;Mid(kod,5,2)) mod 64
                    NameKoder=NameKoder&amp;ChrW( k3 + ( k2 + k1 * 64 ) * 64 )
                    Kod=Right(kod,Len(kod)-6)
                End if
            Else
            NameKoder=NameKoder&amp;Chr(&quot;&amp;H&quot;&amp;Left(kod,2))
            Kod=Right(kod,Len(kod)-2)
            &#039;WshShell.popup(&quot;NameKoder Добавлен очередной КОДОсимвол, теперь &quot;&amp;Cstr(Kod)&amp;&quot; а имя &quot;&amp;NameKoder)
            End If
            WshShell.popup(&quot;NameKoder Добавлен очередной КОДОсимвол, теперь &quot;&amp;Cstr(Kod)&amp;&quot; а имя &quot;&amp;NameKoder)
        Wend

&#039;
&#039;Р—РѕР»СѓС?РєР°-5
Kod=&quot;Р—РѕР»СѓС?РєР°-5&quot;
WshShell.popup Kod&amp;&quot; исходный длина &quot;&amp;Len(kod)

&#039;Перекодирую из двухбайтной UTF  в однобайтную ASC
&#039;Первый байт - код кодировки, второй - код символа
        While len(kod)&gt;0
        WshShell.popup Kod&amp;&quot; Код первого символа &quot;&amp;Asc(Left(kod,1))
            &#039;Проверим ПЕРВЫЙ символ, определим сколько битное кодирование
            If Asc(Left(kod,1))&gt;=128 then 
            &#039;Больше чем байт
                If Asc(Left(kod,1))&lt;224 then 
                &#039;Два байта
                    k1=Asc(Left(kod,1)) mod 32
                    k2 = Asc(Mid(kod,2,1)) mod 64
                    NameKoder=NameKoder&amp;ChrW( k2 + k1 * 64 )
                    Kod=Right(kod,Len(kod)-2)
                Else
                &#039;Три байта
                    k1=Asc(Left(kod,1)) mod 16
                    k2 = Asc(Mid(kod,2,1)) mod 32
                    k2 = Asc(Mid(kod,3,1)) mod 64
                    NameKoder=NameKoder&amp;ChrW( k3 + ( k2 + k1 * 64 ) * 64 )
                    Kod=Right(kod,Len(kod)-3)
                End if
            Else
            NameKoder=NameKoder&amp;Left(kod,1)
            Kod=Right(kod,Len(kod)-1)
            &#039;WshShell.popup(&quot;NameKoder Добавлен очередной КОДОсимвол, теперь &quot;&amp;Cstr(Kod)&amp;&quot; а имя &quot;&amp;NameKoder)
            End If
            WshShell.popup(&quot;NameKoder Добавлен очередной КОДОсимвол, теперь &quot;&amp;Cstr(Kod)&amp;&quot; а имя &quot;&amp;NameKoder)
        Wend</code></pre></div><p>Все это - из моего разборщика почтовых сообщений, в котором компоненты не используются вообще, но упрощено и запускабельно.<br />Когда-то наваял &quot;почтовый парсер&quot; для понимания того, как оно все работает и кодируется. Понимание кодировок приходит сразу и навсегда - из опыта.</p>]]></description>
			<author><![CDATA[null@example.com (RootAdmin)]]></author>
			<pubDate>Wed, 11 Nov 2009 08:03:31 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=30377#p30377</guid>
		</item>
		<item>
			<title><![CDATA[Re: VBScript: конвертация текста из кодировки в кодировку]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=9094#p9094</link>
			<description><![CDATA[<p>По-моему (если только я сам не глючу), во всех примерах всё логично. Оба движка хранят строки в памяти в Юникоде (UTF-16), и объектам их передают тоже в Юникоде.</p><p>В первом примере <strong>fps</strong> метод WriteText пишет строку в Stream, преобразуя её в UTF-8. ReadText читает Stream в переменную (конвертация ANSI -&gt; Unicode), предполагая, что его кодировка Windows-1251. В переменной должна получиться белиберда, но! Т.к. целевой файл открыт как ANSI, при записи в него происходит автоматическое обратное преобразование Unicode -&gt; ANSI с использованием дефолтной кодовой страницы, т.е. той же 1251, и в файле оказывается опять UTF-8.</p><p>Отличие примера <strong>Xameleon</strong>&#039;a в том, что исходная строка уже искажена неправильной конвертацией. бНОПНЯ получается, если ANSI 1251 конвертировать в Юникод с использованием таблицы для КОИ8-Р. Значит, вначале надо сделать обратную конвертацию с той же таблицей КОИ8-Р, чтобы получить исходный, нормальный ANSI-текст. Затем этот текст читается в переменную, т.е. конвертируется из ANSI в Unicode уже с использованием правильной для него таблицы 1251.</p><p>В последнем примере файл 866 читается в переменную inText (преобразование ANSI -&gt; Unicode) с использование дефолтной кодовой страницы (1251). В переменной получается белиберда. Её пишут в Stream (Unicode -&gt; ANSI) с использованием той же 1251, тем самым восстанавливая нормальный текст в 866. Затем его считывают опять в переменную (ANSI -&gt; Unicode), но используя правильную для него таблицу 866. Получается уже нормальный читабельный текст, который и пишут в файл.</p>]]></description>
			<author><![CDATA[null@example.com (YMP)]]></author>
			<pubDate>Fri, 22 Feb 2008 06:59:24 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=9094#p9094</guid>
		</item>
		<item>
			<title><![CDATA[Re: VBScript: конвертация текста из кодировки в кодировку]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=9093#p9093</link>
			<description><![CDATA[<p><em>&gt; P.S. В Коллекции не дискутируем</em></p><p>ОК</p><p>Но дело не в кодировке скрипта.<br />И при загрузке строки из файла результат то-же.</p><p>вот пример на vbs, который перекодирует файл в ОЕМ кодировке в кодировку win-1251.<br />SourceCharset и DestCharset в нем тоже перепутаны</p><div class="codebox"><pre><code> set fs=CreateObject(&quot;Scripting.FilesystemObject&quot;)

 inText=fs.openTextFile(&quot;in.txt&quot;,1).readAll()

 x=strConv(inText,&quot;ibm866&quot;,&quot;windows-1251&quot;)

 fs.openTextFile(&quot;out.txt&quot;,2,true).write(x)

 Function StrConv(Text,SourceCharset,DestCharset)
  Set Stream=CreateObject(&quot;ADODB.Stream&quot;)
  Stream.Type=2
  Stream.Mode=3
  Stream.Open
  Stream.Charset=DestCharset
  Stream.WriteText Text
  Stream.Position=0
  Stream.Charset=SourceCharset
  StrConv=Stream.ReadText
 End Function</code></pre></div>]]></description>
			<author><![CDATA[null@example.com (fps)]]></author>
			<pubDate>Fri, 22 Feb 2008 04:31:55 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=9093#p9093</guid>
		</item>
		<item>
			<title><![CDATA[VBScript: конвертация текста из кодировки в кодировку]]></title>
			<link>http://forum.script-coding.com/viewtopic.php?pid=9090#p9090</link>
			<description><![CDATA[<p>Вопрос по теме в Коллекции <a href="http://forum.script-coding.com/viewtopic.php?id=997">VBScript: пример конвертации текста из кодировки в кодировку</a>.<br /></p><div class="quotebox"><cite>fps пишет:</cite><blockquote><p>переписал предыдущий пример на JS:</p><div class="codebox"><pre><code> var x=strConv(&quot;например&quot;,&quot;windows-1251&quot;,&quot;utf-8&quot;);

 new ActiveXObject(&quot;Scripting.FilesystemObject&quot;).openTextFile(&quot;out.txt&quot;,2,true).write(x);

 function strConv(txt, sourceCharset, destCharset)
 {
  with(new ActiveXObject(&quot;ADODB.Stream&quot;))
  {
   type=2, mode=3, charset=destCharset;
   open();
   writeText(txt);
   position=0, charset=sourceCharset;
   return readText();
  }
 }</code></pre></div><p>работает.</p><p>но, в моем примере <strong>sourceCharset и destCharset поменялись местами</strong> !<br />а если их использовать, как в предыдущем примере, то не работает.</p><p>я глючу?</p></blockquote></div><p>P.S. В Коллекции не дискутируем, см. <a href="http://forum.script-coding.com/rules.html">Правила</a>, раздел 6.<br />Может, дело в кодировке файла самого скрипта?</p>]]></description>
			<author><![CDATA[null@example.com (The gray Cardinal)]]></author>
			<pubDate>Thu, 21 Feb 2008 18:44:41 +0000</pubDate>
			<guid>http://forum.script-coding.com/viewtopic.php?pid=9090#p9090</guid>
		</item>
	</channel>
</rss>
