Windows code pages are sets of characters or code pages (known as character encodings in other operating systems) used in Microsoft Windows from the 1980s and 1990s. Windows code pages were gradually superseded when Unicode was implemented in Windows,[citation needed] although they are still supported both within Windows and other platforms, and still apply when Alt code shortcuts are used.
Current Windows versions support Unicode, new Windows applications should use Unicode (UTF-8) and not 8-bit character encodings.[1]
There are two groups of system code pages in Windows systems: OEM and Windows-native («ANSI») code pages.
(ANSI is the American National Standards Institute.) Code pages in both of these groups are extended ASCII code pages. Additional code pages are supported by standard Windows conversion routines, but not used as either type of system code page.
Alias(es) | ANSI (misnomer) |
---|---|
Standard | WHATWG Encoding Standard |
Extends | ASCII |
Preceded by | ISO 8859 |
Succeeded by | Unicode UTF-16 (in Win32 API) UTF-8 (for files) |
ANSI code pages (officially called «Windows code pages»[2] after Microsoft accepted the former term being a misnomer[3]) are used for native non-Unicode (say, byte oriented) applications using a graphical user interface on Windows systems. The term «ANSI» is a misnomer because these Windows code pages do not comply with any ANSI (American National Standards Institute) standard; code page 1252 was based on an early ANSI draft that became the international standard ISO 8859-1,[3] which adds a further 32 control codes and space for 96 printable characters. Among other differences, Windows code-pages allocate printable characters to the supplementary control code space, making them at best illegible to standards-compliant operating systems.)
Most legacy «ANSI» code pages have code page numbers in the pattern 125x. However, 874 (Thai) and the East Asian multi-byte «ANSI» code pages (932, 936, 949, 950), all of which are also used as OEM code pages, are numbered to match IBM encodings, none of which are identical to the Windows encodings (although most are similar). While code page 1258 is also used as an OEM code page, it is original to Microsoft rather than an extension to an existing encoding. IBM have assigned their own, different numbers for Microsoft’s variants, these are given for reference in the lists below where applicable.
All of the 125x Windows code pages, as well as 874 and 936, are labelled by Internet Assigned Numbers Authority (IANA) as «Windows-number«, although «Windows-936» is treated as a synonym for «GBK». Windows code page 932 is instead labelled as «Windows-31J».[4]
ANSI Windows code pages, and especially the code page 1252, were so called since they were purportedly based on drafts submitted or intended for ANSI. However, ANSI and ISO have not standardized any of these code pages. Instead they are either:[3]
- Supersets of the standard sets such as those of ISO 8859 and the various national standards (like Windows-1252 vs. ISO-8859-1),
- Major modifications of these (making them incompatible to various degrees, like Windows-1250 vs. ISO-8859-2)
- Having no parallel encoding (like Windows-1257 vs. ISO-8859-4; ISO-8859-13 was introduced much later). Also, Windows-1251 follows neither the ISO-standardised ISO-8859-5 nor the then-prevailing KOI-8.
Microsoft assigned about twelve of the typography and business characters (including notably, the euro sign, €) in CP1252 to the code points 0x80–0x9F that, in ISO 8859, are assigned to C1 control codes. These assignments are also present in many other ANSI/Windows code pages at the same code-points. Windows did not use the C1 control codes, so this decision had no direct effect on Windows users. However, if included in a file transferred to a standards-compliant platform like Unix or MacOS, the information was invisible and potentially disruptive.[citation needed]
The OEM code pages (original equipment manufacturer) are used by Win32 console applications, and by virtual DOS, and can be considered a holdover from DOS and the original IBM PC architecture. A separate suite of code pages was implemented not only due to compatibility, but also because the fonts of VGA (and descendant) hardware suggest encoding of line-drawing characters to be compatible with code page 437. Most OEM code pages share many code points, particularly for non-letter characters, with the second (non-ASCII) half of CP437.
A typical OEM code page, in its second half, does not resemble any ANSI/Windows code page even roughly. Nevertheless, two single-byte, fixed-width code pages (874 for Thai and 1258 for Vietnamese) and four multibyte CJK code pages (932, 936, 949, 950) are used as both OEM and ANSI code pages. Code page 1258 uses combining diacritics, as Vietnamese requires more than 128 letter-diacritic combinations. This is in contrast to VISCII, which replaces some of the C0 (i.e. ASCII) control codes.
Early computer systems had limited storage and restricted the number of bits available to encode a character. Although earlier proprietary encodings had fewer, the American Standard Code for Information Interchange (ASCII) settled on seven bits: this was sufficient to encode a 96 member subset of the characters used in the US. As eight-bit bytes came to predominate, Microsoft (and others) expanded the repertoire to 224, to handle a variety of other uses such a box-drawing symbols. The need to provide precomposed characters for the Western European and South American markets required a different character set: Microsoft established the principle of code pages, one for each alphabet. For the segmental scripts used in most of Africa, the Americas, southern and south-east Asia, the Middle East and Europe, a character needs just one byte but two or more bytes are needed for the ideographic sets used in the rest of the world. The code-page model was unable to handle this challenge.
Since the late 1990s, software and systems have adopted Unicode as their preferred character encoding format: Unicode is designed to handle millions of characters. All current Microsoft products and application program interfaces use Unicode internally,[citation needed] but some applications continue to use the default encoding[clarification needed] of the computer’s ‘locale’ when reading and writing text data to files or standard output.[citation needed] Therefore, files may still be encountered that are legible and intelligible in one part of the world but unintelligible mojibake in another.
Microsoft adopted a Unicode encoding (first the now-obsolete UCS-2, which was then Unicode’s only encoding), i.e. UTF-16 for all its operating systems from Windows NT onwards, but additionally supports UTF-8 (aka CP_UTF8
) since Windows 10 version 1803.[5]
UTF-16 uniquely encodes all Unicode characters in the Basic Multilingual Plane (BMP) using 16 bits but the remaining Unicode (e.g. emojis) is encoded with a 32-bit (four byte) code – while the rest of the industry (Unix-like systems and the web), and now Microsoft chose UTF-8 (which uses one byte for the 7-bit ASCII character set, two or three bytes for other characters in the BMP, and four bytes for the remainder).
The following Windows code pages exist:
These nine code pages are all extended ASCII 8-bit SBCS encodings, and were designed by Microsoft for use as ANSI codepages on Windows. They are commonly known by their IANA-registered[6] names as windows-<number>
, but are also sometimes called cp<number>
, «cp» for «code page». They are all used as ANSI code pages; Windows-1258 is also used as an OEM code page.
The Windows-125x series includes nine of the ANSI code pages, and mostly covers scripts from Europe and West Asia with the addition of Vietnam. System encodings for Thai and for East Asian languages were numbered to match similar IBM code pages and are used as both ANSI and OEM code pages; these are covered in following sections.
ID | Description | Relationship to ISO 8859 or other established encodings |
---|---|---|
1250[7][8] | Latin 2 / Central European | Similar to ISO-8859-2 but moves several characters, including multiple letters. |
1251[9][10] | Cyrillic | Incompatible with both ISO-8859-5 and KOI-8. |
1252[11][12] | Latin 1 / Western European | Superset of ISO-8859-1 (without C1 controls). Letter repertoire accordingly similar to CP850. |
1253[13][14] | Greek | Similar to ISO 8859-7 but moves several characters, including a letter. |
1254[15][16] | Turkish | Superset of ISO 8859-9 (without C1 controls). |
1255[17][18] | Hebrew | Almost a superset of ISO 8859-8, but with two incompatible punctuation changes. |
1256[19][20] | Arabic | Not compatible with ISO 8859-6; rather, OEM Code page 708 is an ISO 8859-6 (ASMO 708) superset. |
1257[21][22] | Baltic | Not ISO 8859-4; the later ISO 8859-13 is closely related, but with some differences in available punctuation. |
1258[23][24] | Vietnamese (also OEM) | Not related to VSCII or VISCII, uses fewer base characters with combining diacritics. |
These are also ASCII-based. Most of these are included for use as OEM code pages; code page 874 is also used as an ANSI code page.
- 437 – IBM PC US, 8-bit SBCS extended ASCII.[25] Known as OEM-US, the encoding of the primary built-in font of VGA graphics cards.
- 708 – Arabic, extended ISO 8859-6 (ASMO 708)
- 720 – Arabic, retaining box drawing characters in their usual locations
- 737 – «MS-DOS Greek». Retains all box drawing characters. More popular than 869.
- 775 – «MS-DOS Baltic Rim»
- 850 – «MS-DOS Latin 1». Full (re-arranged) repertoire of ISO 8859-1.
- 852 – «MS-DOS Latin 2»
- 855 – «MS-DOS Cyrillic». Mainly used for South Slavic languages. Includes (re-arranged) repertoire of ISO-8859-5. Not to be confused with cp866.
- 857 – «MS-DOS Turkish»
- 858 – Western European with euro sign
- 860 – «MS-DOS Portuguese»
- 861 – «MS-DOS Icelandic»
- 862 – «MS-DOS Hebrew»
- 863 – «MS-DOS French Canada»
- 864 – Arabic
- 865 – «MS-DOS Nordic»
- 866 – «MS-DOS Cyrillic Russian», cp866. Sole purely OEM code page (rather than ANSI or both) included as a legacy encoding in WHATWG Encoding Standard for HTML5.
- 869 – «MS-DOS Greek 2», IBM869. Full (re-arranged) repertoire of ISO 8859-7.
- 874 – Thai, also used as the ANSI code page, extends ISO 8859-11 (and therefore TIS-620) with a few additional characters from Windows-1252. Corresponds to IBM code page 1162 (IBM-874 is similar but has different extensions).
East Asian multi-byte code pages
edit
These often differ from the IBM code pages of the same number: code pages 932, 949 and 950 only partly match the IBM code pages of the same number, while the number 936 was used by IBM for another Simplified Chinese encoding which is now deprecated and Windows-951, as part of a kludge, is unrelated to IBM-951. IBM equivalent code pages are given in the second column. Code pages 932, 936, 949 and 950/951 are used as both ANSI and OEM code pages on the locales in question.
ID | Language | Encoding | IBM Equivalent | Difference from IBM CCSID of same number | Use |
---|---|---|---|---|---|
932 | Japanese | Shift JIS (Microsoft variant) | 943[26] | IBM-932 is also Shift JIS, has fewer extensions (but those extensions it has are in common), and swaps some variant Chinese characters (itaiji) for interoperability with earlier editions of JIS C 6226. | ANSI/OEM (Japan) |
936 | Chinese (simplified) | GBK | 1386 | IBM-936 is a different Simplified Chinese encoding with a different encoding method, which has been deprecated since 1993. | ANSI/OEM (PRC, Singapore) |
949 | Korean | Unified Hangul Code | 1363 | IBM-949 is also an EUC-KR superset, but with different (colliding) extensions. | ANSI/OEM (Republic of Korea) |
950 | Chinese (traditional) | Big5 (Microsoft variant) | 1373[27] | IBM-950 is also Big5, but includes a different subset of the ETEN extensions, adds further extensions with an expanded trail byte range, and lacks the Euro. | ANSI/OEM (Taiwan, Hong Kong) |
951 | Chinese (traditional) including Cantonese | Big5-HKSCS (2001 ed.) | 5471[28] | IBM-951 is the double-byte plane from IBM-949 (see above), and unrelated to Microsoft’s internal use of the number 951. | ANSI/OEM (Hong Kong, 98/NT4/2000/XP with HKSCS patch) |
A few further multiple-byte code pages are supported for decoding or encoding using operating system libraries, but not used as either sort of system encoding in any locale.
ID | IBM Equivalent | Language | Encoding | Use |
---|---|---|---|---|
1361 | — | Korean | Johab (KS C 5601-1992 annex 3) | Conversion |
20000 | — | Chinese (traditional) | An encoding of CNS 11643 | Conversion |
20001 | — | Chinese (traditional) | TCA | Conversion |
20002 | — | Chinese (traditional) | Big5 (ETEN variant) | Conversion |
20003 | 938 | Chinese (traditional) | IBM 5550 | Conversion |
20004 | — | Chinese (traditional) | Teletext | Conversion |
20005 | — | Chinese (traditional) | Wang | Conversion |
20932 | 954 (roughly) | Japanese | EUC-JP | Conversion |
20936 | 5479 | Chinese (simplified) | GB 2312 | Conversion |
20949, 51949 | 970 | Korean | Wansung (8-bit with ASCII, i.e. EUC-KR)[29] | Conversion |
ID | IBM Equivalent | Description |
---|---|---|
37 | Country Extended Code Page for US, Canada, Netherlands, Portugal, Brazil, Australia, New Zealand[30] | |
500 | Country Extended Code Page for Belgium, Canada and Switzerland | |
870 | EBCDIC Latin-2 | |
875 | EBCDIC Greek | |
1026 | EBCDIC Latin-5 (Turkish) | |
1047 | Country Extended Code Page for Open Systems (POSIX) | |
1140 | Euro-sign Country Extended Code Page for US, Canada, Netherlands, Portugal, Brazil, Australia, New Zealand | |
1141 | Euro-sign Country Extended Code Page for Austria and Germany | |
1142 | Euro-sign Country Extended Code Page for Denmark and Norway | |
1143 | Euro-sign Country Extended Code Page for Finland and Sweden | |
1144 | Euro-sign Country Extended Code Page for Italy | |
1145 | Euro-sign Country Extended Code Page for Spain and Latin America | |
1146 | Euro-sign Country Extended Code Page for UK | |
1147 | Euro-sign Country Extended Code Page for France | |
1148 | Euro-sign Country Extended Code Page for Belgium, Canada and Switzerland | |
1149 | Euro-sign Country Extended Code Page for Iceland | |
20273 | 273 | Country Extended Code Page for Germany |
20277 | 277 | Country Extended Code Page for Denmark/Norway |
20278 | 278 | Country Extended Code Page for Finland/Sweden |
20280 | 280 | Country Extended Code Page for Italy |
20284 | 284 | Country Extended Code Page for Latin America/Spain |
20285 | 285 | Country Extended Code Page for United Kingdom |
20290 | 290 | Japanese Katakana EBCDIC |
20297 | 297 | Country Extended Code Page for France |
20420 | 420 | EBCDIC Arabic |
20423 | 423 | EBCDIC Greek with Extended Latin |
20424 | — | x-EBCDIC-KoreanExtended |
20833 | 833 | Korean EBCDIC for N-Byte Hangul |
20838 | 838 | EBCDIC Thai |
20871 | 871 | Country Extended Code Page for Iceland |
20880 | 880 | EBCDIC Cyrillic (DKOI) |
20905 | 905 | EBCDIC Latin-3 (Maltese, Esperanto and Turkish) |
20924 | 924 | EBCDIC Latin-9 (including Euro sign) for Open Systems (POSIX) |
21025 | 1025 | EBCDIC Cyrillic (DKOI) with section sign |
21027 | (1027) | Japanese EBCDIC (an incomplete implementation of IBM code page 1027,[31] now deprecated)[32] |
ID | IBM Equivalent | Description |
---|---|---|
1200 | 1202, 1203 | Unicode (BMP of ISO 10646, UTF-16LE). Available only to managed applications.[32] |
1201 | 1200, 1201 | Unicode (UTF-16BE). Available only to managed applications.[32] |
12000 | 1234, 1235 | UTF-32. Available only to managed applications.[32] |
12001 | 1232, 1233 | UTF-32. Big-endian. Available only to managed applications.[32] |
65000 | — | Unicode (UTF-7) |
65001 | 1208, 1209 | Unicode (UTF-8) |
Macintosh compatibility code pages
edit
ID | IBM Equivalent | Description |
---|---|---|
10000 | 1275 | Apple Macintosh Roman |
10001 | — | Apple Macintosh Japanese |
10002 | — | Apple Macintosh Chinese (traditional) (BIG-5) |
10003 | — | Apple Macintosh Korean |
10004 | — | Apple Macintosh Arabic |
10005 | — | Apple Macintosh Hebrew |
10006 | 1280 | Apple Macintosh Greek |
10007 | 1283 | Apple Macintosh Cyrillic |
10008 | — | Apple Macintosh Chinese (simplified) (GB 2312) |
10010 | 1285 | Apple Macintosh Romanian |
10017 | — | Apple Macintosh Ukrainian |
10021 | — | Apple Macintosh Thai |
10029 | 1282 | Apple Macintosh Roman II / Central Europe |
10079 | 1286 | Apple Macintosh Icelandic |
10081 | 1281 | Apple Macintosh Turkish |
10082 | 1284 | Apple Macintosh Croatian |
ID | IBM Equivalent | Description |
---|---|---|
28591 | 819, 5100 | ISO-8859-1 – Latin-1 |
28592 | 912 | ISO-8859-2 – Latin-2 |
28593 | 913 | ISO-8859-3 – Latin-3 or South European |
28594 | 914 | ISO-8859-4 – Latin-4 or North European |
28595 | 915 | ISO-8859-5 – Latin/Cyrillic |
28596 | — | ISO-8859-6 – Latin/Arabic |
28597 | 813, 4909, 9005 | ISO-8859-7 – Latin/Greek (1987 edition, i.e. without euro sign, drachma sign or iota subscript)[33] |
28598 | — | ISO-8859-8 – Latin/Hebrew (visual order; 1988 edition, i.e. without LRM and RLM)[33] |
28599 | 920 | ISO-8859-9 – Latin-5 or Turkish |
28600 | 919 | ISO-8859-10 – Latin-6 or Nordic |
28601 | — | ISO-8859-11 – Latin/Thai |
28602 | — | ISO-8859-12 – reserved for Latin/Devanagari but abandoned (not supported) |
28603 | 921 | ISO-8859-13 – Latin-7 or Baltic Rim |
28604 | — | ISO-8859-14 – Latin-8 or Celtic |
28605 | 923 | ISO-8859-15 – Latin-9 |
28606 | — | ISO-8859-16 – Latin-10 or South-Eastern European |
38596 | 1089 | ISO-8859-6-I – Latin/Arabic (logical bidirectional order) |
38598 | 916, 5012 | ISO-8859-8-I – Latin/Hebrew (logical bidirectional order; 1988 edition, i.e. without LRM and RLM)[33] |
ID | IBM Equivalent | Description |
---|---|---|
20105 | 1009 | 7-bit IA5 IRV (Western European)[34][35][36] |
20106 | 1011 | 7-bit IA5 German (DIN 66003)[34][35][37] |
20107 | 1018 | 7-bit IA5 Swedish (SEN 850200 C)[34][35][38] |
20108 | 1016 | 7-bit IA5 Norwegian (NS 4551-2)[34][35][39] |
20127 | 367 | 7-bit ASCII[34][35][40] |
20261 | 1036 | T.61 (T.61-8bit) |
20269 | ? | ISO-6937 |
ID | IBM Equivalent | Description |
---|---|---|
20866 | 878 | Russian – KOI8-R |
21866 | 1167, 1168 | Ukrainian – KOI8-U (or KOI8-RU in some versions)[41] |
Problems arising from the use of code pages
edit
Microsoft strongly recommends using Unicode in modern applications, but many applications or data files still depend on the legacy code pages.
- Programs need to know what code page to use in order to display the contents of (pre-Unicode) files correctly. If a program uses the wrong code page it may show text as mojibake.
- The code page in use may differ between machines, so (pre-Unicode) files created on one machine may be unreadable on another.
- Data is often improperly tagged with the code page, or not tagged at all, making determination of the correct code page to read the data difficult.
- These Microsoft code pages differ to various degrees from some of the standards and other vendors’ implementations. This isn’t a Microsoft issue per se, as it happens to all vendors, but the lack of consistency makes interoperability with other systems unreliable in some cases.
- The use of code pages limits the set of characters that may be used.
- Characters expressed in an unsupported code page may be converted to question marks (?) or other replacement characters, or to a simpler version (such as removing accents from a letter). In either case, the original character may be lost.
- AppLocale – a utility to run non-Unicode (code page-based) applications in a locale of the user’s choice.
- ^ «Unicode and character sets». Microsoft. 2023-06-13. Retrieved 2024-05-27.
- ^ «Code Pages». 2016-03-07. Archived from the original on 2016-03-07. Retrieved 2021-05-26.
- ^ a b c «Glossary of Terms Used on this Site». December 8, 2018. Archived from the original on 2018-12-08.
The term «ANSI» as used to signify Windows code pages is a historical reference, but is nowadays a misnomer that continues to persist in the Windows community. The source of this comes from the fact that the Windows code page 1252 was originally based on an ANSI draft—which became International Organization for Standardization (ISO) Standard 8859-1. «ANSI applications» are usually a reference to non-Unicode or code page–based applications.
- ^ «Character Sets». www.iana.org. Archived from the original on 2021-05-25. Retrieved 2021-05-26.
- ^ hylom (2017-11-14). «Windows 10のInsider PreviewでシステムロケールをUTF-8にするオプションが追加される» [The option to make UTF-8 the system locale added in Windows 10 Insider Preview]. スラド (in Japanese). Archived from the original on 2018-05-11. Retrieved 2018-05-10.
- ^ «Character Sets». IANA. Archived from the original on 2016-12-03. Retrieved 2019-04-07.
- ^ Microsoft. «Windows 1250». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ IBM. «SBCS code page information document CPGID 01250». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ Microsoft. «Windows 1251». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ IBM. «SBCS code page information document CPGID 01251». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ Microsoft. «Windows 1252». Archived from the original on 2013-05-04. Retrieved 2014-07-06.
- ^ IBM. «SBCS code page information document CPGID 01252». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ Microsoft. «Windows 1253». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ IBM. «SBCS code page information document CPGID 01253». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ Microsoft. «Windows 1254». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ IBM. «SBCS code page information document CPGID 01254». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ Microsoft. «Windows 1255». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ IBM. «SBCS code page information document CPGID 01255». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ Microsoft. «Windows 1256». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ IBM. «SBCS code page information document CPGID 01256». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ Microsoft. «Windows 1257». Archived from the original on 2013-03-16. Retrieved 2014-07-06.
- ^ IBM. «SBCS code page information document CPGID 01257». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ Microsoft. «Windows 1258». Archived from the original on 2013-10-25. Retrieved 2014-07-06.
- ^ IBM. «SBCS code page information document CPGID 01258». Archived from the original on 2014-07-14. Retrieved 2014-07-06.
- ^ IBM. «SBCS code page information document — CPGID 00437». Archived from the original on 2016-06-09. Retrieved 2014-07-04.
- ^ «IBM-943 and IBM-932». IBM Knowledge Center. IBM. Archived from the original on 2018-08-18. Retrieved 2020-07-08.
- ^ «Converter Explorer: ibm-1373_P100-2002». ICU Demonstration. International Components for Unicode. Archived from the original on 2021-05-26. Retrieved 2020-06-27.
- ^ «Coded character set identifiers – CCSID 5471». IBM Globalization. IBM. Archived from the original on 2014-11-29.
- ^ Julliard, Alexandre (11 March 2021). «dump_krwansung_codepage: build Korean Wansung table from the KSX1001 file». make_unicode: Generate code page .c files from ftp.unicode.org descriptions. Wine Project. Archived from the original on 2021-05-26. Retrieved 2021-03-14.
- ^ IBM. «SBCS code page information document — CPGID 00037». Archived from the original on 2014-07-14. Retrieved 2014-07-04.
- ^ Steele, Shawn (2005-09-12). «Code Page 21027 «Extended/Ext Alpha Lowercase»«. MSDN. Archived from the original on 2019-04-06. Retrieved 2019-04-06.
- ^ a b c d e «Code Page Identifiers». docs.microsoft.com. Archived from the original on 2019-04-07. Retrieved 2019-04-07.
- ^ a b c Mozilla Foundation. «Relationship with Windows Code Pages». Crate encoding_rs. Docs.rs.
- ^ a b c d e «Code Page Identifiers». Microsoft Developer Network. Microsoft. 2014. Archived from the original on 2016-06-19. Retrieved 2016-06-19.
- ^ a b c d e «Web Encodings — Internet Explorer — Encodings». WHATWG Wiki. 2012-10-23. Archived from the original on 2016-06-20. Retrieved 2016-06-20.
- ^ Foller, Antonin (2014) [2011]. «Western European (IA5) encoding — Windows charsets». WUtils.com — Online web utility and help. Motobit Software. Archived from the original on 2016-06-20. Retrieved 2016-06-20.
- ^ Foller, Antonin (2014) [2011]. «German (IA5) encoding – Windows charsets». WUtils.com – Online web utility and help. Motobit Software. Archived from the original on 2016-06-20. Retrieved 2016-06-20.
- ^ Foller, Antonin (2014) [2011]. «Swedish (IA5) encoding — Windows charsets». WUtils.com — Online web utility and help. Motobit Software. Archived from the original on 2016-06-20. Retrieved 2016-06-20.
- ^ Foller, Antonin (2014) [2011]. «Norwegian (IA5) encoding — Windows charsets». WUtils.com — Online web utility and help. Motobit Software. Archived from the original on 2016-06-20. Retrieved 2016-06-20.
- ^ Foller, Antonin (2014) [2011]. «US-ASCII encoding — Windows charsets». WUtils.com — Online web utility and help. Motobit Software. Archived from the original on 2016-06-20. Retrieved 2016-06-20.
- ^ Nechayev, Valentin (2013) [2001]. «Review of 8-bit Cyrillic encodings universe». Archived from the original on 2016-12-05. Retrieved 2016-12-05.
- National Language Support (NLS) API Reference. Table showing ANSI and OEM codepages per language (from web-archive since Microsoft removed the original page)
- IANA Charset Name Registrations
- Unicode mapping table for Windows code pages
- Unicode mappings of windows code pages with «best fit»
Время на прочтение9 мин
Количество просмотров47K
Введение
Консольные приложения до сих пор остаются наиболее востребованным видом приложений, большинство разработчиков оттачивают архитектуру и бизнес-логику именно в консоли. При этом они нередко сталкиваются с проблемой локализации — русский текст, который вполне адекватно отражается в исходном файле, при выводе на консоль приобретает вид т.н. «кракозябр».
В целом, локализация консоли Windows при наличии соответствующего языкового пакета не представляется сложной. Тем не менее, полное и однозначное решение этой проблемы, в сущности, до сих пор не найдено. Причина этого, главным образом, кроется в самой природе консоли, которая, являясь компонентом системы, реализованным статическим классом System.Console, предоставляет свои методы приложению через системные программы-оболочки, такие как командная строка или командный процессор (cmd.exe), PowerShell, Terminal и другие.
По сути, консоль находится под двойным управлением — приложения и оболочки, что является потенциально конфликтной ситуацией, в первую очередь в части использования кодировок.
Данный материал не предлагает строгий алгоритм действий, а направлен на описание узловых проблем, с которыми неизбежно сталкивается разработчик локализованного консольного приложения, а также некоторые возможные пути их разрешения. Предполагается, что это позволит разработчику сформировать стратегию работы с локализованной консолью и эффективно реализовать существующие технические возможности, большая часть которых хорошо описана и здесь опущена.
Виды консолей
В общем случае функции консоли таковы:
-
управление операционной системой и системным окружением приложений на основе применения стандартных системных устройств ввода-вывода (экран и клавиатура), использования команд операционной системы и/или собственно консоли;
-
запуск приложений и обеспечение их доступа к стандартным потокам ввода-вывода системы, также с помощью стандартных системных устройств ввода-вывода.
Основная консоль Windows — командная строка или иначе командный процессор (CMD). Большие возможности предоставляют оболочки PowerShell (PS), Windows PowerShell (WPS) и Terminal. По умолчанию Windows устанавливает Windows Power Shell мажорной версией до 5, однако предлагает перейти на новую версию — 7-ку, имеющую принципиальное отличие (вероятно, начинающееся с 6-ки) — кроссплатформенность. Terminal — также отдельно уставливаемое приложение, по сути интегратор всех ранее установленных оболочек PowerShell и командной строки.
Отдельным видом консоли можно считать консоль отладки Visual Studio (CMD-D).
Конфликт кодировок
Полностью локализованная консоль в идеале должна поддерживать все мыслимые и немыслимые кодировки приложений, включая свои собственные команды и команды Windows, меняя «на лету» кодовые страницы потоков ввода и вывода. Задача нетривиальная, а иногда и невозможная — кодовые страницы DOS (CP437, CP866) плохо совмещаются с кодовыми страницами Windows и Unicode.
История кодировок здесь: О кодировках и кодовых страницах / Хабр (habr.com)
Исторически кодовой страницей Windows является CP1251 (Windows-1251, ANSI, Windows-Cyr), уверенно вытесняемая 8-битной кодировкой Юникода CP65001 (UTF-8, Unicode Transformation Format), в которой выполняется большинство современных приложений, особенно кроссплатформенных. Между тем, в целях совместимости с устаревшими файловыми системами, именно в консоли Windows сохраняет базовые кодировки DOS — CP437 (DOSLatinUS, OEM) и русифицированную CP866 (AltDOS, OEM).
Совет 1. Выполнять разработку текстовых файлов (программных кодов, текстовых данных и др.) исключительно в кодировке UTF-8. Мир любит Юникод, а кроссплатформенность без него вообще невозможна.
Совет 2. Периодически проверять кодировку, например в текстовом редакторе Notepad++. Visual Studio может сбивать кодировку, особенно при редактировании за пределами VS.
Поскольку в консоли постоянно происходит передача управления от приложений к собственно командному процессору и обратно, регулярно возникает «конфликт кодировок», наглядно иллюстрируемый таблица 1 и 2, сформированных следующим образом:
Были запущены три консоли — CMD, PS и WPS. В каждой консоли менялась кодовая страница с помощью команды CHCP, выполнялась команда Echo c двуязычной строкой в качестве параметра (табл. 1), а затем в консоли запускалось тестовое приложение, исходные файлы которого были созданы в кодировке UTF-8 (CP65001): первая строка формируется и направляется в поток главным модулем, вторая вызывается им же, формируется в подключаемой библиотеке классов и направляется в поток опять главным модулем, третья строка полностью формируется и направляется в поток подключаемой библиотекой.
Команды и код приложения под катом
команды консоли:
-
> Echo ffffff фффффф // в командной строке
-
PS> Echo ffffff фффффф // в PowerShell
-
PS> Echo ffffff ?????? // так выглядит та же команда в Windows PowerShell
код тестового приложения:
using System;
using ova.common.logging.LogConsole;
using Microsoft.Extensions.Logging;
using ova.common.logging.LogConsole.Colors;
namespace LoggingConsole.Test
{
partial class Program
{
static void Main2(string[] args)
{
ColorLevels.ColorsDictionaryCreate();
Console.WriteLine("Hello World! Привет, мир!"); //вывод строки приветствия на двух языках
LogConsole.Write("Лог из стартового проекта", LogLevel.Information);
Console.WriteLine($"8. Active codepage: input {Console.InputEncoding.CodePage}, output {Console.OutputEncoding.CodePage}");
Console.ReadKey();
}
}
}
Командную часть задания все консоли локализовали практически без сбоев во всех кодировках, за исключением: в WPS неверно отображена русскоязычная часть команды во всех кодировках.
Вывод тестового приложения локализован лишь в 50% испытаний, как показано в табл.2.
Сoвет 3. Про PowerShell забываем раз и навсегда. Ну может не навсегда, а до следующей мажорной версии…
По умолчанию Windows устанавливает для консоли кодовые страницы DOS. Чаще всего CP437, иногда CP866. Актуальные версии командной строки cmd.exe способны локализовать приложения на основе русифицированной кодовой страницы 866, но не 437, отсюда и изначальный конфликт кодировок консоли и приложения. Поэтому
Совет 4. Перед запуском приложения необходимо проверить кодовую страницу консоли командой CHCP и ей же изменить кодировку на совместимую — 866, 1251, 65001.
Совет 5. Можно установить кодовую страницу консоли по умолчанию. Кратко: в разделе реестра \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor добавить или изменить значение параметра Autorun на: chcp <номер кодовой страницы>. Очень подробно здесь: Изменить кодовую страницу консоли Windows по умолчанию на UTF-8 (qastack.ru), оригинал на английском здесь: Change default code page of Windows console to UTF-8.
Проблемы консолей Visual Studio
В Visual Studio имеется возможность подключения консолей, по умолчанию подключены командная строка для разработчика и Windows PowerShell для разработчика. К достоинствам можно отнести возможности определения собственных параметров консоли, отдельных от общесистемных, а также запуск консоли непосредственно в директории разработки. В остальном — это обычные стандартные консоли Windows, включая, как показано ранее, установленную кодовую страницу по умолчанию.
Отдельной опцией Visual Studio является встроенная односеансная консоль отладки, которая перехватывает команду Visual Studio на запуск приложения, запускается сама, ожидает компиляцию приложения, запускает его и отдает ему управление. Таким образом, отладочная консоль в течение всего рабочего сеанса находится под управлением приложения и возможность использования команд Windows или самой консоли, включая команду CHCP, не предусмотрена. Более того, отладочная консоль не воспринимает кодовую страницу по умолчанию, определенную в реестре, и всегда запускается в кодировке 437 или 866.
Совет 6. Тестирование приложения целесообразно выполнять во внешних консолях, более дружелюбных к локализации.
Анализ проблем консолей был бы не полон без ответа на вопрос — можно ли запустить консольное приложение без консоли? Можно — любой файл «.exe» запустится двойным кликом, и даже откроется окно приложения. Однако консольное приложение, по крайней мере однопоточное, по двойному клику запустится, но консольный режим не поддержит — все консольные вводы-выводы будут проигнорированы, и приложение завершится
Локализация отладочной консоли Visual Studio
Отладочная консоль — наиболее востребованная консоль разработчика, гораздо более удобная, чем внешняя консоль, поэтому резонно приложить максимум усилий для ее локализации.
На самом деле, правильнее говорить о локализации приложения в консоли — это важное уточнение. Microsoft по этому поводу высказывается недвусмысленно: «Programs that you start after you assign a new code page use the new code page. However, programs (except Cmd.exe) that you started before assigning the new code page will continue to use the original code page». Иными словами, консоль можно локализовать когда угодно и как угодно, но приложение будет локализовано в момент стабилизации взаимодействия с консолью в соответствии с текущей локализацией консоли, и эта локализация сохранится до завершения работы приложения. В связи с этим возникает вопрос — в какой момент окончательно устанавливается связь консоли и приложения?
Важно! Приложение окончательно стабилизирует взаимодействие с консолью в момент начала ввода-вывода в консоль, благодаря чему и появляется возможность программного управления локализацией приложения в консоли — до первого оператора ввода-вывода.
Ниже приведен пример вывода тестового приложения в консоль, иллюстрирующий изложенное. Метод Write получает номера текущих страниц, устанавливает новые кодовые страницы вводного и выводного потоков, выполняет чтение с консоли и записывает выводную строку, содержащий русский текст, в том числе считанный с консоли, обратно в консоль. Операция повторяется несколько раз для всех основных кодовых страниц, упомянутых ранее.
F:\LoggingConsole.Test\bin\Release\net5.0>chcp
Active code page: 1251
F:\LoggingConsole.Test\bin\Release\net5.0>loggingconsole.test
Codepages: current 1251:1251, setted 437:437, ΓΓεΣΦ∞ 5 ±Φ∞ΓεδεΓ ∩ε-≡≤±±ΩΦ: Θ÷≤Ωσ=Θ÷≤Ωσ
Codepages: current 437:437, setted 65001:65001, 5 -: =
Codepages: current 65001:65001, setted 1252:1252, ââîäèì 5 ñèìâîëîâ ïî-ðóññêè: éöóêå=éöóêå
Codepages: current 1252:1252, setted 1251:1251, вводим 5 символов по-русски: йцуке=йцуке
Codepages: current 1251:1251, setted 866:866, ттюфшь 5 ёшьтюыют яю-Ёєёёъш: щЎєъх=щЎєъх
Codepages: current 866:866, setted 1251:1251, вводим 5 символов по-русски: йцуке=йцуке
Codepages: current 1251:1251, setted 1252:1252, ââîäèì 5 ñèìâîëîâ ïî-ðóññêè: éöóêå=éöóêå
F:\LoggingConsole.Test\bin\Release\net5.0>chcp
Active code page: 1252
-
приложение запущено в консоли с кодовыми страницами 1251 (строка 2);
-
приложение меняет кодовые страницы консоли (current, setted);
-
приложение остановлено в консоли с кодовыми страницами 1252 (строка 11, setted);
-
по окончании работы приложения изменения консоли сохраняются (строка 14 — Active codepage 1252);
-
Приложение адекватно локализовано только в случае совпадения текущих кодовых страниц консоли (setted 1251:1251) с начальными кодовыми страницами (строки 8 и 10).
Код тестового приложения под катом
using System;
using System.Runtime.InteropServices;
namespace LoggingConsole.Test
{
partial class Program
{
[DllImport("kernel32.dll")] static extern uint GetConsoleCP();
[DllImport("kernel32.dll")] static extern bool SetConsoleCP(uint pagenum);
[DllImport("kernel32.dll")] static extern uint GetConsoleOutputCP();
[DllImport("kernel32.dll")] static extern bool SetConsoleOutputCP(uint pagenum);
static void Main(string[] args)
{
Write(437);
Write(65001);
Write(1252);
Write(1251);
Write(866);
Write(1251);
Write(1252);
}
static internal void Write(uint WantedIn, uint WantedOut)
{
uint CurrentIn = GetConsoleCP();
uint CurrentOut = GetConsoleOutputCP();
Console.Write($"current {CurrentIn}:{CurrentOut} - текущая кодировка, "); /*wanted {WantedIn}:{WantedOut},*/
SetConsoleCP(WantedIn);
SetConsoleOutputCP(WantedOut);
Console.Write($"setted {GetConsoleCP()}:{GetConsoleOutputCP()} - новая кодировка, ");
Console.Write($"вводим 3 символа по-русски: ");
string str = "" + Console.ReadKey().KeyChar.ToString();
str += Console.ReadKey().KeyChar.ToString();
str += Console.ReadKey().KeyChar.ToString();
Console.WriteLine($"={str}");
}
static internal void Write(uint ChangeTo)
{
Write(ChangeTo, ChangeTo);
}
}
}
Программное управление кодировками консоли — это единственный способ гарантированной адекватной локализацией приложения в консоли. Языки .Net такой возможности не предоставляют, однако предоставляют функции WinAPI: SetConsoleCP(uint numcp) и SetConsoleOutputCP(uint numcp), где numcp — номер кодовой страницы потоков ввода и вывода соответственно. Подробнее здесь: Console Functions — Windows Console | Microsoft Docs. Пример применения консольных функций WInAPI можно посмотреть в тестовом приложении под катом выше.
Совет 7. Обязательный и повторный! Функции SetConsoleCP должны размещаться в коде до первого оператора ввода-вывода в консоль.
Стратегия локализации приложения в консоли
-
Удалить приложение PowerShell (если установлено), сохранив Windows PowerShell;
-
Установить в качестве кодовую страницу консоли по умолчанию CP65001 (utf-8 Unicode) или CP1251 (Windows-1251-Cyr), см. совет 5;
-
Разработку приложений выполнять в кодировке utf-8 Unicode;
-
Контролировать кодировку файлов исходных кодов, текстовых файлов данных, например с помощью Notepad++;
-
Реализовать программное управление локализацией приложения в консоли, пример ниже под катом:
Пример программной установки кодовой страницы и локализации приложения в консоли
using System;
using System.Runtime.InteropServices;
namespace LoggingConsole.Test
{
partial class Program
{
static void Main(string[] args)
{
[DllImport("kernel32.dll")] static extern bool SetConsoleCP(uint pagenum);
[DllImport("kernel32.dll")] static extern bool SetConsoleOutputCP(uint pagenum);
SetConsoleCP(65001); //установка кодовой страницы utf-8 (Unicode) для вводного потока
SetConsoleOutputCP(65001); //установка кодовой страницы utf-8 (Unicode) для выводного потока
Console.WriteLine($"Hello, World!");
}
}
}
10.1. Windows¶
Since Windows 2000, Windows offers a nice Unicode API and supports
non-BMP characters. It uses Unicode strings
implemented as wchar_t*
strings (LPWSTR). wchar_t
is 16 bits long
on Windows and so it uses UTF-16: non-BMP
characters are stored as two wchar_t
(a surrogate pair), and the length of a string is the number of UTF-16 units and
not the number of characters.
Windows 95, 98 and Me had also Unicode strings, but were limited to BMP
characters: they used UCS-2 instead of UTF-16.
10.1.1. Code pages¶
A Windows application has two encodings, called code pages (abbreviated “cp”):
ANSI and OEM code pages. The ANSI code page, CP_ACP
, is used for the
ANSI version of the Windows API to decode byte strings to
character strings and has a number between 874 and 1258. The OEM
code page or “IBM PC” code page, CP_OEMCP
, comes from MS-DOS, is
used for the Windows console, contains glyphs to create
text interfaces (draw boxes) and has a number between 437 and 874. Example of a
French setup: ANSI is cp1252 and OEM is cp850.
There are code page constants:
CP_ACP
: Windows ANSI code page
CP_MACCP
: Macintosh code page
CP_OEMCP
: ANSI code page of the current process
CP_SYMBOL
(42): Symbol code page
CP_THREAD_ACP
: ANSI code page of the current thread
CP_UTF7
(65000): UTF-7
CP_UTF8
(65001): UTF-8
Functions.
- UINT GetACP()¶
-
Get the ANSI code page number.
- UINT GetOEMCP()¶
-
Get the OEM code page number.
- BOOL SetThreadLocale(LCID locale)¶
-
Set the locale. It can be used to change the ANSI code page of current
thread (CP_THREAD_ACP
).
10.1.2. Encode and decode functions¶
Encode and decode functions of <windows.h>
.
- MultiByteToWideChar()
-
Decode a byte string from a code page to a
character string. UseMB_ERR_INVALID_CHARS
flag to
return an error on an undecodable byte sequence.The default behaviour (flags=0) depends on the Windows version:
-
Windows Vista and later: replace undecodable bytes
-
Windows 2000, XP and 2003: ignore undecodable bytes
In strict mode (
MB_ERR_INVALID_CHARS
), the UTF-8
decoder (CP_UTF8
) returns an error on surrogate characters on Windows Vista and later. On Windows XP, the UTF-8
decoder is not strict: surrogates can be decoded in
any mode.The UTF-7 decoder (
CP_UTF7
) only supports flags=0.Examples on any Windows version:
Flags
default (0)
MB_ERR_INVALID_CHARS
0xE9 0x80
, cp1252é€ {U+00E9, U+20AC}
é€ {U+00E9, U+20AC}
0xC3 0xA9
, CP_UTF8é {U+00E9}
é {U+00E9}
0xFF
, cp932{U+F8F3}
decoding error
0xFF
, CP_UTF7{U+FF}
invalid flags
Examples on Windows Vista and later:
Flags
default (0)
MB_ERR_INVALID_CHARS
0x81 0x00
, cp932{U+30FB, U+0000}
decoding error
0xFF
, CP_UTF8{U+FFFD}
decoding error
0xED 0xB2 0x80
, CP_UTF8{U+FFFD, U+FFFD, U+FFFD}
decoding error
Examples on Windows 2000, XP, 2003:
Flags
default (0)
MB_ERR_INVALID_CHARS
0x81 0x00
, cp932{U+0000}
decoding error
0xFF
, CP_UTF8decoding error
decoding error
0xED 0xB2 0x80
, CP_UTF8{U+DC80}
{U+DC80}
Note
The U+30FB character is the Katakana middle dot (・). U+F8F3 code point
is part of a Unicode range reserved for private use (U+E000—U+F8FF). -
- WideCharToMultiByte()
-
Encode a character string to a byte
string. The behaviour on unencodable characters depends on the code page, the Windows version and the flags.Code page
Windows version
Flags
Behaviour
CP_UTF8
2000, XP, 2003
0
Encode surrogates
Vista or later
0
Replace surrogates by U+FFFD
WC_ERR_INVALID_CHARS
Strict
CP_UTF7
all versions
0
Encode surrogates
Others
all versions
0
Replace by similar glyph
WC_NO_BEST_FIT_CHARS
Replace by ? (1)
-
: Strict if you check for pusedDefaultChar pointer.
pusedDefaultChar is not supported by CP_UTF7 or CP_UTF8.
Use
WC_NO_BEST_FIT_CHARS
flag (orWC_ERR_INVALID_CHARS
flag forCP_UTF8
) to have a strict encoder: return an error on unencodable character. By default, if
a character cannot be encoded, it is replaced by
a character with a similar glyph or by “?” (U+003F). For
example, with cp1252, Ł (U+0141) is replaced by L (U+004C).On Windows Vista or later with
WC_ERR_INVALID_CHARS
flag, the
UTF-8 encoder (CP_UTF8
) returns an error on
surrogate characters. The default behaviour (flags=0)
depends on the Windows version: surrogates are replaced by U+FFFD on Windows
Vista and later, and are encoded to UTF-8 on older Windows versions. The
WC_NO_BEST_FIT_CHARS
flag is not supported by the UTF-8 encoder.The
WC_ERR_INVALID_CHARS
flag is only supported by
CP_UTF8
and only on Windows Vista or later.The UTF-7 encoder (
CP_UTF7
) only supports flags=0.
It is not strict: it encodes surrogate characters.Examples (on any Windows version):
Flags
default (0)
WC_NO_BEST_FIT_CHARS
ÿ (U+00FF), cp932
0x79
(y)0x3F
(?)Ł (U+0141), cp1252
0x4C
(L)0x3F
(?)€ (U+20AC), cp1252
0x80
0x80
U+DC80, CP_UTF7
0x2b 0x33 0x49 0x41 0x2d
(+3IA-)invalid flags
Examples on Windows Vista an later:
Flags
default (0)
WC_ERR_INVALID_CHARS
WC_NO_BEST_FIT_CHARS
U+DC80, CP_UTF8
0xEF 0xBF 0xBD
encoding error
invalid flags
Examples on Windows 2000, XP, 2003:
Flags
default (0)
WC_ERR_INVALID_CHARS
WC_NO_BEST_FIT_CHARS
U+DC80, CP_UTF8
0xED 0xB2 0x80
invalid flags
invalid flags
-
Note
MultiByteToWideChar()
and WideCharToMultiByte()
functions
are similar to mbstowcs()
and wcstombs()
functions.
10.1.3. Windows API: ANSI and wide versions¶
Windows has two versions of each function of its API: the ANSI version using
byte strings (A
suffix) and the ANSI code page, and the wide version (W
suffix) using character strings. There are also functions without suffix using TCHAR*
strings:
if the C define _UNICODE
is defined, TCHAR
is
replaced by wchar_t
and the Unicode functions are used; otherwise
TCHAR
is replaced by char
and the ANSI functions are used.
Example:
CreateFileA()
: bytes version, use byte strings
encoded to the ANSI code page
CreateFileW()
: Unicode version, use wide character strings
CreateFile()
:TCHAR
version depending on the
_UNICODE
define
Always prefer the Unicode version to avoid encoding/decoding errors, and use
directly the W
suffix to avoid compiling issues.
Note
There is a third version of the API: the MBCS API (multibyte character
string). Use the TCHAR functions and define _MBCS
to use the MBCS
functions. For example, _tcsrev()
is replaced by _mbsrev()
if _MBCS
is defined, by _wcsrev()
if _UNICODE
is defined, or by _strrev()
otherwise.
10.1.4. Windows string types¶
LPSTR (LPCSTR): byte string,
char*
(const char*
)LPWSTR (LPCWSTR): wide character string,
wchar_t*
(const wchar_t*
)LPTSTR (LPCTSTR): byte or wide character string depending of
_UNICODE
define,TCHAR*
(const TCHAR*
)
10.1.5. Filenames¶
Windows stores filenames as Unicode in the filesystem. Filesystem wide
character POSIX-like API:
- int _wfstat(const wchar_t *filename, struct _stat *statbuf)¶
-
Unicode version of
stat()
.
- FILE *_wfopen(const wchar_t *filename, const wchar_t *mode)¶
-
Unicode version of
fopen()
.
-
int _wopen(const wchar_t *filename, int oflag[
, int pmode
])¶ -
Unicode version of
open()
.
POSIX functions, like fopen()
, use the ANSI code page to encode/decode strings.
10.1.6. Windows console¶
Console functions.
- GetConsoleCP()
-
Get the code page of the standard input (stdin) of the console.
- GetConsoleOutputCP()
-
Get the code page of the standard output (stdout and stderr) of the console.
- WriteConsoleW()
-
Write a character string into the console.
To improve the Unicode support of the console, set the
console font to a TrueType font (e.g. “Lucida Console”) and use the wide
character API
If the console is unable to render a character, it tries to use a
character with a similar glyph. For example, with OEM
code page 850, Ł (U+0141) is replaced by L (U+0041). If no
replacment character can be found, “?” (U+003F) is displayed instead.
In a console (cmd.exe
), chcp
command can be used to display or to
change the OEM code page (and console code page). Changing the
console code page is not a good idea because the ANSI API of the console still
expects characters encoded to the previous console code page.
Note
Set the console code page to cp65001 (UTF-8)
doesn’t improve Unicode support, it is the opposite: non-ASCII are not
rendered correctly and type non-ASCII characters (e.g. using the keyboard)
doesn’t work correctly, especially using raster fonts.
10.1.7. File mode¶
_setmode()
and _wsopen()
are special functions to set the
encoding of a file:
_O_U8TEXT
: UTF-8 without BOM
_O_U16TEXT
: UTF-16 without BOM
_O_WTEXT
: UTF-16 with BOM
fopen()
can use these modes using ccs=
in the file mode:
ccs=UNICODE
:_O_WTEXT
ccs=UTF-8
:_O_UTF8
ccs=UTF-16LE
:_O_UTF16
10.2. Mac OS X¶
Mac OS X uses UTF-8 for the filenames. If a filename is an invalid UTF-8
byte string, Mac OS X returns an error. The filenames are
decomposed to an incompatible variant of the Normal Form
D (NFD). Extract of the Technical Q&A QA1173: “For example,
HFS Plus uses a variant of Normal Form D in which U+2000 through U+2FFF, U+F900
through U+FAFF, and U+2F800 through U+2FAFF are not decomposed.”
10.3. Locales¶
To support different languages and encodings, UNIX and BSD operating systems
have “locales”. Locales are process-wide: if a thread or a library change the
locale, the whole process is impacted.
10.3.1. Locale categories¶
Locale categories:
LC_COLLATE
: compare and sort strings
LC_CTYPE
: decode byte strings and encode
character strings
LC_MESSAGES
: language of messages
LC_MONETARY
: monetary formatting
LC_NUMERIC
: number formatting (e.g. thousands separator)
LC_TIME
: time and date formatting
LC_ALL
is a special category: if you set a locale using this
category, it sets the locale for all categories.
Each category has its own environment variable with the same name. For
example, LC_MESSAGES=C
displays error messages in English. To get the
value of a locale category, LC_ALL
, LC_xxx
(e.g. LC_CTYPE
) or
LANG
environment variables are checked: use the first non empty variable.
If all variables are unset, fallback to the C locale.
Note
The gettext library reads LANGUAGE
, LC_ALL
and LANG
environment
variables (and some others) to get the user language. The LANGUAGE
variable is specific to gettext and is not related to locales.
10.3.2. The C locale¶
When a program starts, it does not get directly the user locale: it uses the
default locale which is called the “C” locale or the “POSIX” locale. It is also
used if no locale environment variable is set. For LC_CTYPE
, the C
locale usually means ASCII, but not always (see the locale
encoding section). For LC_MESSAGES
, the C locale means to speak the
original language of the program, which is usually English.
10.3.3. Locale encoding¶
For Unicode, the most important locale category is LC_CTYPE
: it is used to
set the “locale encoding”.
To get the locale encoding:
Copy the current locale:
setlocale(LC_CTYPE, NULL)
Set the current locale encoding to the user preference:
setlocale(LC_CTYPE, "")
Use
nl_langinfo(CODESET)
if availableor
setlocale(LC_CTYPE, NULL)
For the C locale, nl_langinfo(CODESET)
returns ASCII, or an alias
to this encoding (e.g. “US-ASCII” or “646”). But on FreeBSD, Solaris and
Mac OS X, codec functions (e.g. mbstowcs()
) use
ISO 8859-1 even if nl_langinfo(CODESET)
announces ASCII encoding.
AIX uses ISO 8859-1 for the C locale (and nl_langinfo(CODESET)
returns "ISO8859-1"
).
10.3.4. Locale functions¶
<locale.h>
functions.
- char *setlocale(category, NULL)¶
-
Get the value of the specified locale category.
- char *setlocale(category, name)
-
Set the value of the specified locale category.
<langinfo.h>
functions.
- char *nl_langinfo(CODESET)¶
-
Get the name of the locale encoding.
<stdlib.h>
functions.
- size_t mbstowcs(wchar_t *dest, const char *src, size_t n)¶
-
Decode a byte string from the locale encoding to a character string. The decoder is strict: it returns an error on undecodable byte sequence. If available, prefer the reentrant version:
mbsrtowcs()
.
- size_t wcstombs(char *dest, const wchar_t *src, size_t n)¶
-
Encode a character string to a byte string in
the locale encoding. The encoder is strict : it returns an error if a character cannot by encoded. If available, prefer the reentrant version:
wcsrtombs()
.
mbstowcs() and wcstombs() are strict and don’t support
error handlers.
Note
“mbs” stands for “multibyte string” (byte string) and “wcs” stands for “wide
character string”.
On Windows, the “locale encoding” are the ANSI and OEM code pages. A Windows program uses the user preferred code pages at startup,
whereas a program starts with the C locale on UNIX.
10.4. Filesystems (filenames)¶
10.4.1. CD-ROM and DVD¶
CD-ROM uses the ISO 9660 filesystem which stores filenames as byte
strings. This filesystem is very restrictive: only A-Z, 0-9, _ and
“.” are allowed. Microsoft has developed the Joliet extension: store
filenames as UCS-2, up to 64 characters (BMP only).
It was first supported by Windows 95. Today, all operating systems are able
to read it.
UDF (Universal Disk Format) is the filesystem of DVD: it stores filenames as
character strings.
10.4.2. Microsoft: FAT and NTFS filesystems¶
MS-DOS uses the FAT filesystems (FAT 12, FAT 16, FAT 32): filenames are stored
as byte strings. Filenames are limited to 8+3 characters (8 for
the name, 3 for the extension) and displayed differently depending on the
code page (mojibake issue).
Microsoft extended its FAT filesystem in Windows 95: the Virtual FAT (VFAT)
supports “long filenames”, filenames are stored as UCS-2, up to
255 characters (BMP only). Starting at Windows 2000, non-BMP characters can be used: UTF-16 replaces UCS-2 and the limit is now
255 UTF-16 units.
The NTFS filesystem stores filenames using UTF-16 encoding.
10.4.3. Apple: HFS and HFS+ filesystems¶
HFS stores filenames as byte strings.
HFS+ stores filenames as UTF-16: the maximum length is 255
UTF-16 units.
10.4.4. Others¶
JFS and ZFS also use Unicode.
The ext family (ext2, ext3, ext4) store filenames as byte strings.
Code Pages, Character Encodings from Software Vendors and Standards Bodies
Here you can find character set and code page information from software vendors
(Microsoft, HP, IBM, Sun, etc.) and international standards organizations (e.g. ISO, ECMA, INCITS, etc.).
Push any «button» and you will be taken either to the chart of a code page
provided by the vendor, or the vendor’s web page of links to code page charts.
This gives you fast access to popular code pages, as well as access to more complete lists of code page charts.
Organization
The links are (mostly) organized by vendor or standard organization.
Some code pages are listed redundantly, usually because the code page is being described by different vendors.
Sometimes the difference is important. For example, one vendor’s view of a code page may be different from
another’s. Certainly character conversion or mapping tables may be very different. Sometimes a code page has been
updated and one vendor is still referring to an earlier version of the code page.
Character Encodings, Transformation Formats, Double-Byte, Multi-byte, UTF…
Note that a «code page» is also known by various other names:
codepage, encoding, charset, character set, coded character set, (CCS),
graphic character set, character map et al. Some of these have
more specific names DBCS (double-byte character set), MBCS
(multi-byte character set). Some encodings are the result of
transformations, and are known as transformation formats,
examples include Unicode UTF-8, UTF-16, UTF-32.
Unicode UTF-16 Surrogate Code Points, or Supplementary Characters
TABLE OF CONTENTS
Unicode Standards Organizations Assorted web pages The Go To Guys Czyborra’s Site Great Sites China’s GB18030 Hong Kong Supplementary Character Set (HKSCS) Library of Congress MAchine Readable Catalog (MARC) |
Microsoft’s ISO code pages Microsoft Windows code pages Microsoft double-byte character sets Microsoft DOS code pages |
IBM ICU IBM’s ISO code pages IBM Windows code pages IBM Asian code pages IBM DOS code pages |
Push A Button To Get Code Page Information
Assorted Web PagesI18n Guy’s Hiragana Unicode Chart Dik Winter’s Character Set History Piotr Trzcionkowski’s Polish code page site (in Polish) Cyrillic.com Character Sets I18nGuru’s Character Sets page VT320, VT102, VT52, Heath-19 DEC Terminals VT100, VT220, VT320 Kostis’ Character Sets Kostis’ Apple Macintosh Roman Japanese Encoding Differences Koichi Yasuoka’s Character Tables |
Unicode ChartsUnicode Charts Unicode character name index UTF-32 (TR-19) Character Encoding Model (TR-17) Basic Latin Latin-1 Supplement Latin Extended-A Combining Diacritical Marks Greek Cyrillic Hebrew I18n Guy’s Hebrew Unicode Chart Arabic Currency Symbols Hangul Jamo Hiragana I18n Guy’s Hiragana Unicode Chart Katakana |
Standards OrganizationsISO INCITS ECMA Standards ISO 6429 = ECMA-48 (pdf) ISO/IEC International register of coded character sets to be used with escape sequences IANA Character Set Registry RFC Index RFC 1555 Hebrew Character Encoding for Internet Messages RFC 1556 Handling of Bi-directional Texts in MIME RFC 1556 defines ISO-8859-6-e, ISO-8859-6-i, ISO-8859-8-e,ISO-8859-8-i Armenian Character Sets ArmSCII Thai TIS 620-2533 Annotated reference to the Thai implementations |
The Go To GuysMichael Everson’s site Ken Lunde’s CJK.inf Ken Lunde’s Character set server Mark Davis’s site |
Czyborra’s Sitewww.czyborra.com/charsets is offline. Fortunately, Kevin Atkinson has Roman Czyborra’s site Czyborra’s Vendor Codepages Czyborra’s Vietnamese page Czyborra’s ASCII/ISO 646 page Czyborra’s ISO 8859 Alphabet Soup So vat’s Unicode? Chicken soup? |
Great SitesFrank da Cruz’s Character Sets Frank da Cruz’s Character Set Tables Korpela’s Tutorial on character code issues Korpela’s Character and encoding site |
GB18030 Web PagesICU’s Markus Scherer on GB18030 Sun on GB18030-2000 Microsoft GB18030 Support Package (in GB2312) (Adobe) Dirk Meyer’s Summary of GB18030 |
Hong Kong Supplementary Character Set (HKSCS)Hong Kong Supplementary Character Set (HKSCS) Hong Kong ITF on ISO 10646 |
MARC BibliographicMARC 21 MARC-8 MARC UCS (Unicode) MARC Code Tables |
Here are many transcoding tables expressed in XML files using the IBM ICUCharacter Conversion Data IBM Character DataIBM Code pages (Appendix F) IBM Character lists (Appendix I) IBM Sort Sequences (Appendix C) |
IBM
|
IBM
|
In the following web pages, leadbytes are indicated by light Microsoft
|
Microsoft Windows
|
Microsoft’s
|
IBM DOS Code pagesCP 00437 (IBM PC) USA CP 00850 (IBM PC) Multilingual CP 00851 (IBM PC) Greece CP 00852 Latin-2 PC CP 00855 (IBM PC) Cyrillic CP 00856 (IBM PC) Hebrew CP 00857 (IBM PC) Turkey CP 00860 (IBM PC) Portugal CP 00861 (IBM PC) Iceland CP 00862 (IBM PC) Israel CP 00863 (IBM PC) Canadian French CP 00864 (IBM PC) Arabic CP 00865 (IBM PC) Nordic CP 00866 (IBM PC) Cyrillic #2 CP 00869 (IBM PC) Greece CP 00870 Latin-2 Multilingual CP 00874 (IBM PC) Thai Extended |
Microsoft OEM
|
IBM Asian Code pagesI18n Guy’s Hiragana Unicode Chart CP 00290 (EBCDIC) Japanese (Katakana) Non-extended CP 00290 (EBCDIC) Japanese (Katakana) Extended CP 00833 (EBCDIC) Korea Extended CP 00836 (EBCDIC) Simplified Chinese Extended CP 00891 (IBM PC) Korea CP 00895 Japan 7-Bit CP 00897 (IBM PC) Japan PC #1 CP 00903 (IBM PC) People’s Republic of China (PRC) CP 00904 (IBM PC) Republic of China (ROC) CP 00905 (EBCDIC) Turkey Extended CP CP 01027 (EBCDIC) Japanese (Latin) Extended CP 01040 (IBM PC) Korean Extended CP 01041 (IBM PC) Japanese Extended CP 01042 (IBM PC) Simplified Chinese Extended CP 01043 (IBM PC) Traditional Chinese CP 01088 (IBM PC) Korean CP 01114 Traditional Chinese (Big5) CP 01115 Simplified Chinese (GB) |
Copyright © 2002, 2003, 2004, 2005 Tex Texin. All rights reserved.
Top of page
Кодовая страница (англ. code page) — таблица, сопоставляющая каждому значению байта некоторый символ (или его отсутствие). Обычно код символа имеет размер 8 бит, так что кодовая страница может содержать максимум 256 символов, из чего вытекает резкая недостаточность всякой 8-битной кодовой страницы для представления многоязычных текстов. К тому же часть символов используется как управляющие, из-за чего число печатных символов редко превышает 223[1].
Исторически термин code page был введён корпорацией IBM; сменные кодовые страницы использовались для поддержки различных языков (имеющих алфавитные системы письма). В последнее время имеется путаница между термином «кодовая страница» и более общим понятием набора символов (кодировки).
Кодовые страницы сегодня[править | править код]
В настоящее время в основном используются кодировки двух типов: совместимые с ASCII и совместимые с EBCDIC[2], с подавляющим преобладанием первых.
В ASCII-совместимых кодировках фиксированы коды 95 печатных символов и 33 управляющих, а остальные 128 кодовых позиций используются для различных символов, не входящих в ASCII.
Для кодирования текстов на русском языке (то есть букв кириллицы) наиболее широко применяются следующие кодовые страницы:
- Windows-1251, она же Microsoft code page 1251 (CP1251) — в системах Windows;
- Семейство кодовых страниц KOI8;
- Альтернативная кодировка, она же IBM code page 866 — в системах DOS, а также в текстовых окнах Microsoft Windows (см. ниже);
- MacCyrillic — на компьютерах Macintosh.
Использование различных кодовых страниц создаёт много неудобств как для пользователей, так и для программистов. При попытке прочесть текстовый файл при помощи кодовой страницы, несовместимой с той в которой он был создан, возникают кракозябры[en]. В последние годы получил широкое распространение Unicode как альтернатива традиционным кодовым страницам.
В системе Microsoft Windows[править | править код]
В системах Microsoft Windows кодовые страницы являются важным компонентом локализации, задаваемым в ключах реестра HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage\[3].
Исторически (в системах Windows 3.x и Windows 9x) имелось два типа кодовых страниц. Кодовые страницы «ANSI»[4] (англ. ANSI code page, в реестре: ACP), также называемые Windows[5] — родные кодовые страницы Windows. Содержат много символов типографики, но почти не содержат псевдографику по причине того, что предназначены для использования в графическом окружении. Впоследствии корпорация Microsoft признала, что использование имени ANSI было вызвано недоразумением.[6] К кодировкам «ANSI»/Windows относят, в частности, Windows-1252 и вышеупомянутую Windows-1251. Microsoft также относит к кодовым страницам кодовые таблицы, некоторые позиции которых требуют второго (завершающего) байта для формирования символа, то есть допускающие двухбайтовое представление некоторых символов[7], хотя они, строго говоря, являются уже кодировками с переменной длиной символа.
Кодировки OEM (англ. OEM code page, в реестре: OEMCP) основаны на CP437 и содержат VGA-совместимую псевдографику. Вышеупомянутая альтернативная кодировка известна в Windows как CP866.
Начиная с Windows NT появился третий класс кодовых страниц: кодировки Macintosh (англ. Macintosh code page, в реестре: MACCP), совместимых с MacOS.
Примечания[править | править код]
- ↑ Одним из немногих исключений является кодировка VISCII для вьетнамской латиницы, совместимая с ASCII за вычетом шести кодов в зоне управляющих символов, заменённых на буквы, см. RFC 1456. Таким образом, она содержит 229 печатных символов.
- ↑
Кодировки на базе EBCDIC (например, ДКОИ-8) используются только на некоторых мэйнфреймах. - ↑ REG: CurrentControlSet, PART 1, Microsoft (англ.)
- ↑ Кодовые страницы в Visual C++, MSDN
- ↑ Code Pages, MSDN
- ↑ MSDN: Glossary of Terms (недоступная ссылка). Дата обращения 2 марта 2010. Архивировано 28 марта 2016 года.
- ↑ Windows code pages Архивная копия от 2 мая 2014 на Wayback Machine, MSDN