← 中文资源

简体中文版本

UTF-16 编解码 rune

用 unicode/utf16 编码与解码:BMP 外字符拆成代理对,IsSurrogate 识别代理码元,孤立代理退回 U+FFFD。

阅读英文原文

实现说明

UTF-16 编解码 rune可以归结为函数 main。

使用要点

  • 每一步打印都带着自己的标签:code units:、first units:、high surrogate:。

常见问题

运行「UTF-16 编解码 rune」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 code units:、first units:、high surrogate: 标签标明各步骤。

核心语句

r, size := utf16.DecodeRune(rune(units[len(units)-2]), rune(units[len(units)-1]))

代码示例

package main

import (
	"fmt"
	"unicode/utf16"
)

func main() {
	text := "Go 语言 🚀"

	// Encode:rune → UTF-16 码元,BMP 外字符拆成代理对
	units := utf16.Encode([]rune(text))
	fmt.Println("code units:", len(units), "runes:", len([]rune(text)))
	fmt.Println("first units:", units[:3])

	// IsSurrogate 判断 0xD800-0xDFFF 区间的代理码元
	last := rune(units[len(units)-2])
	fmt.Println("high surrogate:", utf16.IsSurrogate(last))

	// Decode:码元 → rune,自动合并合法代理对
	back := string(utf16.Decode(units))
	fmt.Println("roundtrip:", back == text, back)

	// DecodeRune 处理单个位置并返回消耗的码元数
	r, size := utf16.DecodeRune(rune(units[len(units)-2]), rune(units[len(units)-1]))
	fmt.Printf("decoded rune: %c size: %d\n", r, size)

	// 孤立代理返回替换符 U+FFFD,大小为 1
	bad, badSize := utf16.DecodeRune(0xD800, 'A')
	fmt.Printf("lone surrogate: U+%04X size: %d\n", bad, badSize)
}