U-00000000 - U-0000007F: 0xxxxxxx U-00000080 - U-000007FF: 110xxxxx 10xxxxxx U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx ← 漢字在此範圍 U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx ...
首字節前導 1 的個數即總字節數。
4F60 → 二進制 1001111011000001110 + 0100 = 11100100 (0xE4)10 + 111101 = 10111101 (0xBD)10 + 100000 = 10100000 (0xA0)E4 BD A0& 0x1F 取低 5 位,左移 12 位& 0x3F 取低 6 位,左移 6 位& 0x3F 取低 6 位/** UTF-8 單字符 → Unicode 十六進制字符串 */
function utf8_str_to_unicode($utf8_str) {
$unicode = 0;
$unicode = (ord($utf8_str[0]) & 0x1F) << 12;
$unicode |= (ord($utf8_str[1]) & 0x3F) << 6;
$unicode |= (ord($utf8_str[2]) & 0x3F);
return dechex($unicode);
}
/** Unicode 十六進制字符串 → UTF-8 單字符 */
function unicode_to_utf8($unicode_str) {
$code = intval(hexdec($unicode_str)); // 必須轉整型
$ord1 = 0xE0 | ($code >> 12);
$ord2 = 0x80 | (($code >> 6) & 0x3F);
$ord3 = 0x80 | ($code & 0x3F);
return chr($ord1) . chr($ord2) . chr($ord3);
}
// 測試
$utf8_str = '我'; // Unicode: 6211
$unicode_str = '4f60'; // 你
echo utf8_str_to_unicode($utf8_str) . "<br/>"; // 6211
echo unicode_to_utf8($unicode_str); // 你
utf8_to_unicode_str/unicode_str_to_utf8json_encode($str, JSON_UNESCAPED_UNICODE) 等內建函數