如何将Unicode码点转换为UTF-8十六进制字节?附代码示例
Unicode码点转UTF-8十六进制字节的代码示例
Python 实现
通过将十六进制码点映射为Unicode字符,再编码为UTF-8字节并格式化输出:
def unicode_codepoint_to_utf8_hex(codepoint_hex): # 将十六进制码点转为整数 codepoint = int(codepoint_hex, 16) # 转为Unicode字符后编码为UTF-8字节 utf8_bytes = chr(codepoint).encode('utf-8') # 格式化每个字节为两位大写十六进制,并用空格分隔 return ' '.join(f'{byte:02X}' for byte in utf8_bytes) # 示例调用 print(unicode_codepoint_to_utf8_hex('1F606')) # 输出: F0 9F 98 86
注意:输入的码点需为不带U+前缀的十六进制字符串,例如1F606而非U+1F606
PHP(兼容Hacklang)实现
借助多字节字符处理函数完成码点到UTF-8字节的转换:
function unicodeCodepointToUtf8Hex(string $codepointHex): string { // 十六进制码点转整数 $codepoint = hexdec($codepointHex); // 从UTF-32编码生成对应Unicode字符 $char = mb_chr($codepoint, 'UTF-32'); // 转换为UTF-8字节序列 $utf8Bytes = mb_convert_encoding($char, 'UTF-8', 'UTF-32'); // 遍历每个字节转为大写十六进制并拼接 $hexSegments = []; for ($i = 0; $i < strlen($utf8Bytes); $i++) { $hexSegments[] = strtoupper(dechex(ord($utf8Bytes[$i]))); } return implode(' ', $hexSegments); } // 示例调用 echo unicodeCodepointToUtf8Hex('1F606'); // 输出: F0 9F 98 86
注意:PHP环境需启用mbstring扩展,Hacklang环境可直接使用上述函数
内容的提问来源于stack exchange,提问作者Connie Shi
相关产品推荐
相关产品推荐

