UTF-16 Encode And Decode Runes

Encode runes to UTF-16 code units, detect surrogate pairs for characters outside the BMP, and decode units back into a string.

GoData Integrity

Code

gosnippet
31 lines
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)
}

Where the work concentrates

UTF-16 Encode And Decode Runes comes down to the function main.

Applying it

The run emits 6 labeled sections — code units:, first units:, high surrogate:, roundtrip:, decoded rune:, lone surrogate: U+ — one per step.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does UTF-16 Encode And Decode Runes print when run?
The script runs standalone; its 6 labeled outputs include `code units:`, `first units:`, `high surrogate:`.