unicode - 手动将 unicode 代码点转换为 UTF-8 和 UTF-16

标签 unicode utf-8 utf-16

我即将参加大学编程考试,其中一个部分是关于 unicode 的。

我已经彻底检查了这个问题的答案,而且我的讲师毫无用处,所以这没有帮助,所以这是你们可能提供帮助的最后手段。

问题类似于:

The string 'mЖ丽' has these unicode codepoints U+006D, U+0416 and U+4E3D, with answers written in hexadecimal, manually encode the string into UTF-8 and UTF-16.

任何帮助都将不胜感激,因为我正在努力解决这个问题。

最佳答案

哇。一方面,我很高兴知道大学类(class)所教导的现实是字符编码是一项艰苦的工作,但实际上了解 UTF-8 编码规则听起来像是期望很高。 (对学生pass the Turkey test有帮助吗?)

到目前为止,我见过的关于将 UCS 代码点编码为 UTF-8 的规则的最清晰描述来自 utf-8(7)许多 Linux 系统上的联机帮助页:

Encoding
   The following byte sequences are used to represent a
   character.  The sequence to be used depends on the UCS code
   number of the character:

   0x00000000 - 0x0000007F:
       0xxxxxxx

   0x00000080 - 0x000007FF:
       110xxxxx 10xxxxxx

   0x00000800 - 0x0000FFFF:
       1110xxxx 10xxxxxx 10xxxxxx

   0x00010000 - 0x001FFFFF:
       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

   [... removed obsolete five and six byte forms ...]

   The xxx bit positions are filled with the bits of the
   character code number in binary representation.  Only the
   shortest possible multibyte sequence which can represent the
   code number of the character can be used.

   The UCS code values 0xd800–0xdfff (UTF-16 surrogates) as well
   as 0xfffe and 0xffff (UCS noncharacters) should not appear in
   conforming UTF-8 streams.

记住图表的“压缩”版本可能会更容易:

损坏代码点的初始字节以 1 开头,并添加填充 1+0 。后续字节开始 10 .

0x80      5 bits, one byte
0x800     4 bits, two bytes
0x10000   3 bits, three bytes

您可以通过记下可以用新表示中允许的位填充多少空间来得出范围:

2**(5+1*6) == 2048       == 0x800
2**(4+2*6) == 65536      == 0x10000
2**(3+3*6) == 2097152    == 0x200000

我知道可以记住导出图表的规则比记住图表本身更容易。希望您也能善于记住规则。 :)

更新

构建完上面的图表后,您可以通过查找其范围、从十六进制转换为二进制、根据上述规则插入位,然后转换回十六进制,将输入的 Unicode 代码点转换为 UTF-8:

U+4E3E

这符合0x00000800 - 0x0000FFFF范围( 0x4E3E < 0xFFFF ),因此表示形式为:

   1110xxxx 10xxxxxx 10xxxxxx

0x4E3E100111000111110b 。将这些位放入 x上面(从右边开始,我们将用 0 填充开头的缺失位):

   1110x100 10111000 10111110

有一个x开头留下的位置,填写 0 :

   11100100 10111000 10111110

bits to hex 转换:

   0xE4 0xB8 0xBE

关于unicode - 手动将 unicode 代码点转换为 UTF-8 和 UTF-16,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240055/

相关文章:

linux - dompdf 生成的 pdf 中不显示欧元符号

c - 将多字节字符映射到它们的 unicode 点表示

python - 如何从 Python 脚本中更改环境变量 LANG?

java - 如何阅读非 BMP (astral) Unicode 增补字符(代码点)

oracle - PL/SQL : UTL_HTTP POST with UTF8 string results in broken characters

c++ - 如何转换 UTF-8 <-> UTF16 便携

java - 在 Java 中检测(或最佳猜测)传入的字符串编码

python - 为什么空字符串 '' 在 utf-16 中编码为 2 个字节,而在 utf-8 或 ascii 中编码为 0 个字节?

c++11 - 在 C++11 中遍历 UTF-8 字符串

visual-studio - 在 VisualStudio 中将所有 *.cs 文件转换为 unicode