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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.