Python 3 utf-8编码似乎错了?

GZa*_*man 2 python unicode python-3.x

我在过去使用Python 3.2时已经搞砸了,但现在我在python中遇到了一个关于utf-8编码的混乱局面.
例如,假设我有这段代码:

'?'.encode()
Run Code Online (Sandbox Code Playgroud)

结果是b'\xd7\x90'(或0xD790),但这是错误的:希伯来字符Alef的utf-8编码应该是0x5D0.
但是,使用utf-16作为编码返回正确的十六进制值,前缀为0xFFFE:

'?'.encode('utf-16')
Run Code Online (Sandbox Code Playgroud)

这回来了b'\xff\xfe\xd0\x05'.

我觉得好像我遗漏了一些基本的理解,
SO用户,请帮助教育我!

phi*_*hag 8

אunicode 代码点是U + 05D0,或101 1101 0000二进制.11位代码点ABCDEFGHIJK的UTF-8编码

110A BCDE  10FG HIJK
# i.e.
1101 0111  1001 0000 # binary
 d    7     9    0   # hex
Run Code Online (Sandbox Code Playgroud)

或者,用Python表示法b'\xd7\x90'.


Ign*_*ams 6

0x5d0根本不是编码; 它只是一个数字.是的,希伯来字母ALEF是U + 05D0,但是UTF-8不是代码点到字节的转录.相反,它使用每个字节的MSb中的某个固定位组,并使用来自码点值的可变位数填充LSb.

0x5d0 = 101 1101 0000
      = 10111 010000
Run Code Online (Sandbox Code Playgroud)

插入110xxxxx 10xxxxxx我们得到:

11010111 10010000 = 0xd7 0x90
Run Code Online (Sandbox Code Playgroud)