this is the logo image

浅谈UTF-8编码

UTF-8是一个变长度的编码方式,它使用一个到四个8位的字节编码一个Unicode码点,编码的第一个字节的high-order bits预示着编码有几个字节,如下图所示:

UTF-8编码示意图
Figure 1.UTF-8编码模型
总结如下: 举个例子,中文字符串“世界”的Unicode码点为\u4e16\u754c, 十进制表示为19990,30028,值在2048-65535之间,故编码各有三个字节,如图所示其 内存字节为:e4 b8 96 e7 95 8c。
世界UTF-8内存模型
Figure 2."世界"字符串内存模型
光说不练假把式,下面就用go语言验证一下,废话不多说,代码如下(file name main.go):
                package main
                
                import "fmt"

                func main() {
                    s := "世界"
                    r := []rune(s)
                    // Print every rune in the string s of its hexidecimal and decimal representation
                    fmt.Printf("%x\t%d\n", r, r)
                    // Print the string s
                    fmt.Println(string(r))
                    // Print ervery bytes of the string s in hexidecimal separated by space
	                fmt.Printf("% x\n", s)
                }
            
在command line运行:go run main.go,结果如下:
运行结果
Figure 3.运行结果