de-vraag
  • Вопросы
  • Метки
  • Пользователи
Оповещения
Вознаграждения
Регистрация
После регистрации, сможете получать уведомления об ответах и комментариях на Ваши вопросы.
Вход
Если у Вас уже есть аккаунт, войдите чтобы проверить новые уведомления.
Тут будут вознаграждения за добавленные вопросы, ответы и комментарий.
Дополнительно
Источник
Редактировать
 Rekha
Rekha
Вопрос

Что значит сказать «Модифицированная кодировка UTF-8»?

Что значит сказать «Модифицированная кодировка UTF-8»? Как это отличается от обычного кодирования UTF-8?

9 2011-10-27T19:07:13+00:00 3
Программирование
java
BalusC
27-го октября 2011 в 7:10
2011-10-27T19:10:32+00:00
Дополнительно
Источник
Редактировать
#56791796

Это подробно описано в javadoc DataInput :

Modified UTF-8

Implementations of the DataInput and DataOutput interfaces represent Unicode strings in a format that is a slight modification of UTF-8. (For information regarding the standard UTF-8 format, see section 3.9 Unicode Encoding Forms of The Unicode Standard, Version 4.0). Note that in the following tables, the most significant bit appears in the far left-hand column.

... (some tables, please click the javadoc link to see yourself) ...

The differences between this format and the standard UTF-8 format are the following:

  • The null byte '\u0000' is encoded in 2-byte format rather than 1-byte, so that the encoded strings never have embedded nulls.
  • Only the 1-byte, 2-byte, and 3-byte formats are used.
  • Supplementary characters are represented in the form of surrogate pairs.

Как читать это подробно описано в javadoc <код> DataInput # readUTF () :

readUTF

String readUTF()
           throws IOException

Reads in a string that has been encoded using a modified UTF-8 format. The general contract of readUTF is that it reads a representation of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String.

First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method . This integer value is called the UTF length and specifies the number of additional bytes to be read. These bytes are then converted to characters by considering them in groups. The length of each group is computed from the value of the first byte of the group. The byte following a group, if any, is the first byte of the next group.

If the first byte of a group matches the bit pattern 0xxxxxxx (where x means "may be 0 or 1"), then the group consists of just that byte. The byte is zero-extended to form a character.

If the first byte of a group matches the bit pattern 110xxxxx, then the group consists of that byte a and a second byte b. If there is no byte b (because byte a was the last of the bytes to be read), or if byte b does not match the bit pattern 10xxxxxx, then a UTFDataFormatException is thrown. Otherwise, the group is converted to the character:

(char)(((a& 0x1F) << 6) | (b & 0x3F))

If the first byte of a group matches the bit pattern 1110xxxx, then the group consists of that byte a and two more bytes b and c. If there is no byte c (because byte a was one of the last two of the bytes to be read), or either byte b or byte c does not match the bit pattern 10xxxxxx, then a UTFDataFormatException is thrown. Otherwise, the group is converted to the character:

(char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))

If the first byte of a group matches the pattern 1111xxxx or the pattern 10xxxxxx, then a UTFDataFormatException is thrown.

If end of file is encountered at any time during this entire process, then an EOFException is thrown.

After every group has been converted to a character by this process, the characters are gathered, in the same order in which their corresponding groups were read from the input stream, to form a String, which is returned.

The writeUTF method of interface DataOutput may be used to write data that is suitable for reading by this method.

8
0
Tules
27-го октября 2011 в 7:09
2011-10-27T19:09:34+00:00
Дополнительно
Источник
Редактировать
#56791795

Язык программирования Java, который использует UTF-16 для внутреннего текстового представления, поддерживает нестандартную модификацию UTF-8 для сериализации строк. Эта кодировка называется модифицированной UTF-8. Между измененным и стандартным UTF-8 существует две отличия. Первое отличие состоит в том, что нулевой символ (U + 0000) кодируется двумя байтами вместо одного, а именно 11000000 10000000.

3
0
TofuBeer
27-го октября 2011 в 7:09
2011-10-27T19:09:33+00:00
Дополнительно
Источник
Редактировать
#56791794

Probably this: http://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8

"При нормальном использовании язык программирования Java поддерживает стандартные   UTF-8 при чтении и записи строк через InputStreamReader и   OutputStreamWriter. Однако он использует модифицированный UTF-8 для объекта   сериализации, для Java Native Interface и для   встраивание константных строк в файлы классов. "

1
0
Похожие сообщества 11
pro.jvm
pro.jvm
5 862 пользователей
Сообщество разработчиков Java Scala Kotlin Groovy Clojure Чат для нач-их: @javastart Наш канал: @proJVM Вакансии: @jvmjobs @jvmjobschat Конфы: @jvmconf ⚠️ Оффтоп -> @flood ❌Переход на личности ❌Троллинг ❌Реклама ❌HH (вакансии) ❌Варез
Открыть telegram
learn.java
learn.java
5 163 пользователей
Чат для начинающих и не только Статистика: https://combot.org/chat/-1001083535868 Основной чат - @jvmchat
Открыть telegram
Java & Co
Java & Co
4 454 пользователей
Можно обсуждать с матом и без всё, что касается жабы, вплоть до холиваров. НЕ ИМЕЕТ ОТНОШЕНИЯ К САЙТУ JAVARUSH.RU ПРАВИЛА - https://t.me/javarush/179171 Вакансии сюда - https://telegram.me/joinchat/B7IzvUCnfo6d8t3yIxKguQ По вопросам - @thedude
Открыть telegram
pro.JVM Jobs Chat
pro.JVM Jobs Chat
2 513 пользователей
Чат для обсуждения вакансий на JVM языках. Правила: - Никакого спама - Никакого троллинга и оскорблений участников - Размещение вакансий только через канал Канал для вакансий: @jvmjobs Основной чат: @jvmchat Наши друзья: @scala_jobs, @scala_jobs_feed
Открыть telegram
Java/Kotlin and more
Java/Kotlin and more
2 025 пользователей
чат о Java/Kotlin и связанных технологиях. We're discussing: job, tech questions etc. languages: russian, java, eng, kotlin Ссылка на чат: t.me/springframeworkio
Открыть telegram
Java Underground
Java Underground
1 581 пользователей
Библиотека по Java https://t.me/javalib Наше сообщество ВК: https://vk.com/javatutorial Вакансии и резюме свои строго в этот канал: https://t.me/job_java
Открыть telegram
Добавить вопрос
Категории
Все
Технологий
Культура / Отдых
Жизнь / Искусство
Наука
Профессии
Бизнес
Пользователи
Все
Новые
Популярные
1
Roxana Elizabeth CASTILLO Avalos
Зарегистрирован 5 дней назад
2
Hideo Nakagawa
Зарегистрирован 5 дней назад
3
Sergiy Tytarenko
Зарегистрирован 1 неделю назад
4
shoxrux azadov
Зарегистрирован 1 неделю назад
5
Koreets Koreytsev
Зарегистрирован 1 неделю назад
© de-vraag 2022
Источник
stackoverflow.com
под лицензией cc by-sa 3.0 с атрибуцией