Що таке кодування символів Як ANSI і Unicode, і як вони відрізняються?
ASCII, UTF-8, ISO-8859… Можливо, ви бачили ці дивні псевдоніми плаваючі навколо, але що вони насправді мають на увазі? Читайте далі, як ми пояснюємо, що таке кодування символів і як ці скорочення відносяться до звичайного тексту, який ми бачимо на екрані.
Фундаментальні будівельні блоки
Коли ми говоримо про письмову мову, ми говоримо про букви, що є будівельними блоками слів, які потім будують речення, абзаци і так далі. Букви – це символи, які представляють звуки. Коли ви говорите про мову, ви говорите про групи звуків, які об’єднуються, щоб сформувати якийсь сенс. Кожна мовна система має складний набір правил і визначень, які регулюють ці значення. Якщо у вас є слово, це марно, якщо ви не знаєте, з якої мови це, і ви використовуєте його з іншими, які говорять на цій мові.
(Порівняння скриптів Grantha, Tulu і Malayalam, зображення з Вікіпедії)
У світі комп’ютерів ми використовуємо термін «характер». Характер є свого роду абстрактним поняттям, що визначається специфічними параметрами, але він є фундаментальною одиницею значення. Латинська “A” не є такою ж, як грецька “альфа” або арабська “alif”, тому що вони мають різні контексти – вони з різних мов і мають трохи різні вимови – так що ми можемо сказати, що вони різні символи. Візуальне представлення символу називається «гліфом», а різні набори гліфів називаються шрифтами. Групи символів належать до “набору” або “репертуару”.
Коли ви вводите абзац і змінюєте шрифт, ви не змінюєте фонетичні значення букв, ви змінюєте їх вигляд. Це просто косметика (але не важлива!). Деякі мови, як стародавній єгипетський і китайський, мають ідеограми; вони являють собою цілі ідеї замість звуків, і їх вимова може змінюватися в часі і відстані. Якщо ви заміните одного символу на іншого, ви замінюєте ідею. Це більше, ніж просто зміна букв, вона змінює ідеограму.
Кодування символів
(Зображення з Вікіпедії)
Коли ви вводите щось на клавіатурі або завантажуєте файл, як комп’ютер знає, що відображати? Для цього призначено кодування символів. Текст на вашому комп’ютері не є буквами, це серія парних алфавітно-цифрових значень. Кодування символів діє як ключ, для якого значення відповідають символам, подібно до того, як орфографія диктує, які звуки відповідають яким буквам. Код Морзе – це свого роду кодування символів. Тут пояснюється, як групи довгих і коротких одиниць, такі як звукові сигнали, являють собою символи. У коді Морзе символи – це тільки англійські літери, цифри і повні зупинки. Є багато кодувань символів комп’ютера, які перекладаються на літери, цифри, знаки акценту, знаки пунктуації, міжнародні символи тощо..
Часто на цю тему використовується термін «кодові сторінки». Це, по суті, кодування символів, яке використовують конкретні компанії, часто з незначними змінами. Наприклад, кодова сторінка Windows 1252 (раніше відома як ANSI 1252) є модифікованою формою ISO-8859-1. Вони в основному використовуються як внутрішня система для посилання на стандартні та модифіковані кодування символів, які є специфічними для тих самих систем. На початку кодування символів було не так важливо, тому що комп’ютери не спілкувалися один з одним. Зі зростанням інтернету до виникнення та створення мереж, що стає звичайним явищем, він стає все більш важливим для нашого повсякденного життя без нас навіть усвідомлення цього.
Багато різних типів
(Зображення із sarah sosiak)
Існує багато різних кодувань символів, і для цього є багато причин. Яке кодування символів, яке ви вирішите використовувати, залежить від ваших потреб. Якщо ви спілкуєтеся російською мовою, має сенс використовувати кодування символів, яке добре підтримує кирилицю. Якщо ви спілкуєтеся по-корейськи, то вам знадобиться те, що добре представляє хангул і ханья. Якщо ви математик, то ви хочете чогось, що має всі наукові і математичні символи, представлені добре, а також грецькі і латинські гліфи. Якщо ви – жартівник, можливо, ви отримаєте користь від перевернутого тексту. І якщо ви хочете, щоб усі ці типи документів були переглянуті будь-якою людиною, ви бажаєте, щоб кодування було досить поширеним і легко доступним.
Давайте подивимося на деякі з найбільш поширених.
(Витяг з таблиці ASCII, Зображення з asciitable.com)
- ASCII – Американський стандартний код для обміну інформацією є одним із старих кодувань символів. Спочатку він був розроблений на основі телеграфних кодів і з часом розвивався, щоб включити більше символів і деяких застарілих недрукованих контрольних символів. Це, напевно, настільки ж базове, як ви можете отримати з точки зору сучасних систем, оскільки воно обмежується латинським алфавітом без акцентованих символів. Його 7-бітне кодування дозволяє використовувати лише 128 символів, тому в світі існує кілька неофіційних варіантів.
- ISO-8859 – Найбільш широко використовуваною групою кодування символів Міжнародної організації зі стандартизації є номер 8859. Кожне специфічне кодування позначається числом, часто префіксом описового назви, наприклад, ISO-8859-3 (Latin-3), ISO-8859-6 (латинська / арабська). Це надмножина ASCII, що означає, що перші 128 значень у кодуванні такі ж, як ASCII. Це 8-бітний, проте, і дозволяє використовувати 256 символів, тому він згортається звідти і включає в себе набагато більш широкий масив символів, причому кожна специфічна кодування фокусується на іншому наборі критеріїв. Latin-1 містив купу букв і символів з акцентом, але пізніше був замінений переглянутим набором під назвою Latin-9, який містить оновлені гліфи, такі як символ євро..
(Витяг з тибетського сценарію, Unicode v4, від unicode.org)
- Unicode – Цей стандарт кодування спрямований на універсальність. В даний час вона включає в себе 93 сценаріїв, організованих у декілька блоків, у яких багато інших робіт. Unicode працює по-іншому, ніж інші набори символів, оскільки замість безпосереднього кодування гліфу кожна величина спрямовується далі до “кодової точки”. Це шістнадцяткові значення, які відповідають символам, але самі гліфи надаються програмою окремо , наприклад веб-браузер. Ці кодові точки зазвичай зображені таким чином: U + 0040 (що перекладається як ‘@’). Конкретні кодування в стандарті Unicode – UTF-8 і UTF-16. UTF-8 намагається забезпечити максимальну сумісність з ASCII. Це 8-бітний, але дозволяє використовувати всі символи за допомогою механізму заміни і декількох пар значень на символ. UTF-16 розколює ідеальну сумісність з ASCII для більш повної 16-бітової сумісності зі стандартом.
- ISO-10646 – Це не фактичне кодування, а лише набір символів Unicode, стандартизований ISO. Це в основному важливо, тому що це репертуар символів, який використовується HTML. Деякі з більш просунутих функцій, що надаються Unicode, які дозволяють сортування та справа наліво разом зі сценаріями зліва направо, відсутні. Тим не менш, він працює дуже добре для використання в Інтернеті, оскільки дозволяє використовувати широкий спектр сценаріїв і дозволяє браузеру інтерпретувати гліфи. Це полегшує локалізацію.
Що потрібно використовувати для кодування?
Ну, ASCII працює для більшості англомовних, але не для багатьох інших. Найчастіше ви побачите ISO-8859-1, який працює для більшості західноєвропейських мов. Інші версії ISO-8859 працюють для кириличної, арабської, грецької або інших специфічних сценаріїв. Однак, якщо ви хочете відобразити декілька сценаріїв в одному документі або на одній веб-сторінці, UTF-8 дозволяє набагато краще сумісності. Вона також працює дуже добре для людей, які використовують правильні знаки пунктуації, математичні символи або символи поза манжетою, такі як квадрати та прапорці.
(Кілька мов в одному документі, Знімок екрана gujaratsamachar.com)
У кожному наборі є недоліки. ASCII обмежений у своїх пунктуаційних знаках, тому він не працює неймовірно добре для типографічно правильних редагувань. Коли-небудь набираєте копіювати / вставляти з Word лише для того, щоб мати деяке дивне поєднання гліфів? Це недолік стандарту ISO-8859, або, більш коректно, його передбачуваної взаємодії з кодами сторінок операційної системи (ми дивимося на вас, Microsoft!). Головним недоліком UTF-8 є відсутність належної підтримки редагування та публікації додатків. Інша проблема полягає в тому, що браузери часто не інтерпретують і просто відображають знак порядку байтів кодуваного символу UTF-8. Це призводить до відображення небажаних гліфів. І, звичайно, оголошення одного кодування та використання символів з іншого, без правильного декларування / посилання на веб-сторінку, ускладнює для браузерів правильне відображення їх у пошукових системах, а також їх відповідний індекс.
Для ваших власних документів, рукописів і т. П. Ви можете використовувати все, що потрібно для виконання роботи. Що стосується мережі, то, здається, більшість людей погоджується на використання UTF-8 версії, яка не використовує позначку порядку байтів, але це не зовсім одностайно. Як бачите, кодування кожного символу має власне використання, контекст, сильні та слабкі сторони. Як кінцевий користувач, вам, мабуть, не доведеться мати справу з цим, але тепер ви можете зробити додатковий крок вперед, якщо ви так виберете.
What’s the difference between ASCII and Unicode?
What’s the exact difference between Unicode and ASCII? ASCII has a total of 128 characters (256 in the extended set). Is there any size specification for Unicode characters?
33k 26 26 gold badges 146 146 silver badges 173 173 bronze badges
5,876 6 6 gold badges 18 18 silver badges 19 19 bronze badges
9 Answers 9
ASCII defines 128 characters, which map to the numbers 0–127. Unicode defines (less than) 2 21 characters, which, similarly, map to numbers 0–2 21 (though not all numbers are currently assigned, and some are reserved).
Unicode is a superset of ASCII, and the numbers 0–127 have the same meaning in ASCII as they have in Unicode. For example, the number 65 means “Latin capital ‘A'”.
Because Unicode characters don’t generally fit into one 8-bit byte, there are numerous ways of storing Unicode characters in byte sequences, such as UTF-32 and UTF-8.
170k 26 26 gold badges 171 171 silver badges 255 255 bronze badges
469k 92 92 gold badges 884 884 silver badges 1.1k 1.1k bronze badges
@riderBill: What now? Which 3 bits are you talking about? There are no bits in Unicode. Just codepoints.
@riderBill: again: which “3 bytes” are you talking about now? 🙂 (None of this has to do with Unicode. Unicode is only about assigning meaning to numbers, it’s not about bits and bytes.)
@riderBill: Unicode does not “use between 1 and 4 bytes”. Unicode is an assignment of meaning to numbers. It doesn’t use any bytes. There are certain standardized encoding schemes to represent Unicode codepoints as a stream of bytes, but they are orthogonal to Unicode as a character set. (Yes, feel free to delete as you please.)
@CleanCrispCode Unicode is actually a superset of ISO-8859-1, which is itself a superset of ASCII. Sometimes that’s useful to know.
To clarify, Unicode character set itself is a superset of ISO-8859-1 character set, but UTF-8 encoding is not a superset of ISO-8859-1 encoding but ASCII encoding.
Understanding why ASCII and Unicode were created in the first place helped me understand the differences between the two.
ASCII, Origins
As stated in the other answers, ASCII uses 7 bits to represent a character. By using 7 bits, we can have a maximum of 2^7 (= 128) distinct combinations * . Which means that we can represent 128 characters maximum.
Wait, 7 bits? But why not 1 byte (8 bits)?
The last bit (8th) is used for avoiding errors as parity bit. This was relevant years ago.
Most ASCII characters are printable characters of the alphabet such as abc, ABC, 123, ?&!, etc. The others are control characters such as carriage return, line feed, tab, etc.
See below the binary representation of a few characters in ASCII:
0100101 -> % (Percent Sign - 37) 1000001 -> A (Capital letter A - 65) 1000010 -> B (Capital letter B - 66) 1000011 -> C (Capital letter C - 67) 0001101 -> Carriage Return (13) See the full ASCII table over here.
ASCII was meant for English only.
What? Why English only? So many languages out there!
Because the center of the computer industry was in the USA at that time. As a consequence, they didn’t need to support accents or other marks such as á, ü, ç, ñ, etc. (aka diacritics).
ASCII Extended
Some clever people started using the 8th bit (the bit used for parity) to encode more characters to support their language (to support “é”, in French, for example). Just using one extra bit doubled the size of the original ASCII table to map up to 256 characters (2^8 = 256 characters). And not 2^7 as before (128).
10000010 -> é (e with acute accent - 130) 10100000 -> á (a with acute accent - 160) The name for this “ASCII extended to 8 bits and not 7 bits as before” could be just referred as “extended ASCII” or “8-bit ASCII”.
As @Tom pointed out in his comment below there is no such thing as “extended ASCII” yet this is an easy way to refer to this 8th-bit trick. There are many variations of the 8-bit ASCII table, for example, the ISO 8859-1, also called ISO Latin-1.
Unicode, The Rise
ASCII Extended solves the problem for languages that are based on the Latin alphabet. what about the others needing a completely different alphabet? Greek? Russian? Chinese and the likes?
We would have needed an entirely new character set. that’s the rational behind Unicode. Unicode doesn’t contain every character from every language, but it sure contains a gigantic amount of characters (see this table).
You cannot save text to your hard drive as “Unicode”. Unicode is an abstract representation of the text. You need to “encode” this abstract representation. That’s where an encoding comes into play.
Encodings: UTF-8 vs UTF-16 vs UTF-32
This answer does a pretty good job at explaining the basics:
- UTF-8 and UTF-16 are variable length encodings.
- In UTF-8, a character may occupy a minimum of 8 bits.
- In UTF-16, a character length starts with 16 bits.
- UTF-32 is a fixed length encoding of 32 bits.
UTF-8 uses the ASCII set for the first 128 characters. That’s handy because it means ASCII text is also valid in UTF-8.
This is obvious for some, but just in case. We have seven slots available filled with either 0 or 1 (Binary Code). Each can have two combinations. If we have seven spots, we have 2 * 2 * 2 * 2 * 2 * 2 * 2 = 2^7 = 128 combinations. Think about this as a combination lock with seven wheels, each wheel having two numbers only.
Source: Wikipedia, this great blog post and Mocki.co where I initially posted this summary.
There is no text but encoded text. Some encodings are very straightforward, particularly for characters sets with
Thank you. I notice everywhere ASCII tables show character codes as 0-127 but UTF-8 tables show the codes as hex and not integers. Is there a reason for this? Why don’t UTF-X tables show 0-127/255/65535 versus 00-AF? Does this mean anything?
Thank you for you answer. Quick question: ‘In UTF-16, a character length starts with 16 bits’ — Does this mean that alphanumeric characters can’t be represented by UTF-16 since they are only 8-bit characters?
Great answer, only I’ve got one issue – does Polish really use a different alphabet? I thought we use the same one as English, just with some additional letters?
Good Explanation. It will be appropriate to explain little bit on Unicode. Unicode is one large standard effort which has catalogued and specified a number and character relationship for virtually all characters and symbols of every major language in use, which is hundreds of thousands of characters.
ASCII has 128 code points, 0 through 127. It can fit in a single 8-bit byte, the values 128 through 255 tended to be used for other characters. With incompatible choices, causing the code page disaster. Text encoded in one code page cannot be read correctly by a program that assumes or guessed at another code page.
Unicode came about to solve this disaster. Version 1 started out with 65536 code points, commonly encoded in 16 bits. Later extended in version 2 to 1.1 million code points. The current version is 6.3, using 110,187 of the available 1.1 million code points. That doesn’t fit in 16 bits anymore.
Encoding in 16-bits was common when v2 came around, used by Microsoft and Apple operating systems for example. And language runtimes like Java. The v2 spec came up with a way to map those 1.1 million code points into 16-bits. An encoding called UTF-16, a variable length encoding where one code point can take either 2 or 4 bytes. The original v1 code points take 2 bytes, added ones take 4.
Another variable length encoding that’s very common, used in *nix operating systems and tools is UTF-8, a code point can take between 1 and 4 bytes, the original ASCII codes take 1 byte the rest take more. The only non-variable length encoding is UTF-32, takes 4 bytes for a code point. Not often used since it is pretty wasteful. There are other ones, like UTF-1 and UTF-7, widely ignored.
An issue with the UTF-16/32 encodings is that the order of the bytes will depend on the endian-ness of the machine that created the text stream. So add to the mix UTF-16BE, UTF-16LE, UTF-32BE and UTF-32LE.
Having these different encoding choices brings back the code page disaster to some degree, along with heated debates among programmers which UTF choice is “best”. Their association with operating system defaults pretty much draws the lines. One counter-measure is the definition of a BOM, the Byte Order Mark, a special codepoint (U+FEFF, zero width space) at the beginning of a text stream that indicates how the rest of the stream is encoded. It indicates both the UTF encoding and the endianess and is neutral to a text rendering engine. Unfortunately it is optional and many programmers claim their right to omit it so accidents are still pretty common.
931k 148 148 gold badges 1.7k 1.7k silver badges 2.6k 2.6k bronze badges
java provides support for Unicode i.e it supports all world wide alphabets. Hence the size of char in java is 2 bytes. And range is 0 to 65535.
@Mark, 256 is when you consider all of ASCII range (including extended)
@Thinker-101 There is no such thing as “extended ASCII”. There are numerous encodings that differently define what bytes 128-255 mean. ASCII defines what bytes 0-127 mean.
ASCII has 128 code positions, allocated to graphic characters and control characters (control codes).
Unicode has 1,114,112 code positions. About 100,000 of them have currently been allocated to characters, and many code points have been made permanently noncharacters (i.e. not used to encode any character ever), and most code points are not yet assigned.
The only things that ASCII and Unicode have in common are: 1) They are character codes. 2) The 128 first code positions of Unicode have been defined to have the same meanings as in ASCII, except that the code positions of ASCII control characters are just defined as denoting control characters, with names corresponding to their ASCII names, but their meanings are not defined in Unicode.
Sometimes, however, Unicode is characterized (even in the Unicode standard!) as “wide ASCII”. This is a slogan that mainly tries to convey the idea that Unicode is meant to be a universal character code the same way as ASCII once was (though the character repertoire of ASCII was hopelessly insufficient for universal use), as opposite to using different codes in different systems and applications and for different languages.
Unicode as such defines only the “logical size” of characters: Each character has a code number in a specific range. These code numbers can be presented using different transfer encodings, and internally, in memory, Unicode characters are usually represented using one or two 16-bit quantities per character, depending on character range, sometimes using one 32-bit quantity per character.
30.9k 22 22 gold badges 107 107 silver badges 132 132 bronze badges
198k 37 37 gold badges 274 274 silver badges 396 396 bronze badges
I think the most common encoding for Unicode is UTF-8 these days. UTF-8 encodes most of the code points in 1, 2 or 3 bytes.
ASCII and Unicode are two character encodings. Basically, they are standards on how to represent difference characters in binary so that they can be written, stored, transmitted, and read in digital media. The main difference between the two is in the way they encode the character and the number of bits that they use for each. ASCII originally used seven bits to encode each character. This was later increased to eight with Extended ASCII to address the apparent inadequacy of the original. In contrast, Unicode uses a variable bit encoding program where you can choose between 32, 16, and 8-bit encodings. Using more bits lets you use more characters at the expense of larger files while fewer bits give you a limited choice but you save a lot of space. Using fewer bits (i.e. UTF-8 or ASCII) would probably be best if you are encoding a large document in English.
One of the main reasons why Unicode was the problem arose from the many non-standard extended ASCII programs. Unless you are using the prevalent page, which is used by Microsoft and most other software companies, then you are likely to encounter problems with your characters appearing as boxes. Unicode virtually eliminates this problem as all the character code points were standardized.
Another major advantage of Unicode is that at its maximum it can accommodate a huge number of characters. Because of this, Unicode currently contains most written languages and still has room for even more. This includes typical left-to-right scripts like English and even right-to-left scripts like Arabic. Chinese, Japanese, and the many other variants are also represented within Unicode. So Unicode won’t be replaced anytime soon.
In order to maintain compatibility with the older ASCII, which was already in widespread use at the time, Unicode was designed in such a way that the first eight bits matched that of the most popular ASCII page. So if you open an ASCII encoded file with Unicode, you still get the correct characters encoded in the file. This facilitated the adoption of Unicode as it lessened the impact of adopting a new encoding standard for those who were already using ASCII.
1.ASCII uses an 8-bit encoding while Unicode uses a variable bit encoding. 2.Unicode is standardized while ASCII isn’t. 3.Unicode represents most written languages in the world while ASCII does not. 4.ASCII has its equivalent within Unicode.