美文网首页
golang 格式化打印-utf-8编码规则

golang 格式化打印-utf-8编码规则

作者: 豆瓣奶茶 | 来源:发表于2019-01-11 19:31 被阅读14次

示例程序

func main() {
    var s byte = '?'
    fmt.Println(s) //63
    //输出 2/8/10 进制格式
    fmt.Printf("%b,%o,%d\n", s, s, s) // 111111,77,63
    // 以16进制输出字符串
    fmt.Printf("%x\n", "hex this")
    // 输出数值所表示的 Unicode 字符
    fmt.Printf("%c\n", 63)
    //输出数值所表示的 Unicode 字符(带单引号)。对于无法显示的字符,将输出其转义字符。
    fmt.Printf("%q\n", 63)
    //输出 Unicode 码点(例如 U+1234,等同于字符串 "U+%04X" 的显示结果)
    fmt.Printf("%U\n", 63)
}

在线编码转换
http://tools.jb51.net/transcoding/unicode_chinese

汉字字符集编码查询
http://www.qqxiuzi.cn/bianma/zifuji.php

在线进制转换
https://tool.lu/hexconvert/

在线Unicode和UTF编码转换
https://www.qqxiuzi.cn/bianma/Unicode-UTF.php

UTF-8编码规则

https://blog.csdn.net/sandyen/article/details/1108168

编码示例

func main() {
    var s rune = '好'
    fmt.Printf("%d\n",s) // 22909
    buf := bytes.NewBufferString("hello")
    fmt.Println(buf.Bytes()) // [104 101 108 108 111]
    buf.WriteRune(s)
    fmt.Println(buf.Bytes()) // [104 101 108 108 111 229 165 189]
}

什么会写入三个字节?[229 165 189]
我们先看看的编码方式
http://tool.oschina.net/hexconvert




将Unicode编码597D转化为UTF-8编码

可以看到utf-8编码是E5A58D,这是十六进制的,我们转为为10进制

我们要的是字节数组,所以需要将11100101 10100101 10111101拆成字节,然后再转化成10进制显示。



相关文章

网友评论

      本文标题:golang 格式化打印-utf-8编码规则

      本文链接:https://www.haomeiwen.com/subject/gwhfdqtx.html