MySQL CHAR() Function and UTF8 Output?

时光总嘲笑我的痴心妄想 提交于 2019-11-30 21:45:57

You are confusing UTF-8 with Unicode.

0x00FC is the Unicode code point for ü:

mysql> select char(0x00FC using ucs2);
+----------------------+
| char(0x00FC using ucs2) |
+----------------------+
| ü                   | 
+----------------------+

In UTF-8 encoding, 0x00FC is represented by two bytes:

mysql> select char(0xC3BC using utf8);
+-------------------------+
| char(0xC3BC using utf8) |
+-------------------------+
| ü                      | 
+-------------------------+

UTF-8 is merely a way of encoding Unicode characters in binary form. It is meant to be space efficient, which is why ASCII characters only take a single byte, and iso-8859-1 characters such as ü only take two bytes. Some other characters take three or four bytes, but they are much less common.

Adding to Martin's answer:

  1. You can use an "introducer" instead of the CHAR() function. To do this, you specify the encoding, prefixed with an underscore, before the code point:

    _utf16 0xFC
    

    or:

    _utf16 0x00FC
    
  2. If the goal is to specify the code point instead of the encoded byte sequence, then you need to use an encoding in which the code point value just happens to be the encoded byte sequence. For example, as shown in Martin's answer, 0x00FC is both the code point value for ü and the encoded byte sequence for ucs2 / utf16 (they are effectively the same encoding for BMP characters, but I prefer to use "utf16" as it is consistent with "utf8" and "utf32", consistent in the "utf" theme).

    But, utf16 only works for BMP characters (code points U+0000 - U+FFFF) in terms of specifying the code point value. If you want a Supplementary Character, then you will need to use the utf32 encoding. Not only does _utf32 0xFC return ü, but:

    _utf32 0x1F47E
    

    returns: 👾

For more details on these options, plus Unicode escape sequences for other languages and platforms, please see my post:

Unicode Escape Sequences Across Various Languages and Platforms (including Supplementary Characters)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!