golang实现base64转码unicode转为utf-8
时间: 2023-05-29 14:05:24 浏览: 308
Golang中的Unicode与字符串示例详解
package main
import (
"encoding/base64"
"fmt"
"unicode/utf16"
"unicode/utf8"
)
func main() {
// 转码前的unicode字符串
unicodeStr := "你好,世界!"
// 将unicode字符串转为UTF-8字节切片
utf8Bytes := make([]byte, len(unicodeStr)*3)
utf8Len := utf8.EncodeRune(utf8Bytes, rune(unicodeStr[0]))
utf8Bytes = utf8Bytes[:utf8Len]
for _, r := range unicodeStr[1:] {
utf8Len = utf8.EncodeRune(utf8Bytes[utf8Len:], r)
utf8Bytes = utf8Bytes[:utf8Len]
}
// 将UTF-8字节切片进行base64编码
base64Str := base64.StdEncoding.EncodeToString(utf8Bytes)
// 将base64编码后的字符串解码为UTF-8字节切片
decodedBytes, err := base64.StdEncoding.DecodeString(base64Str)
if err != nil {
fmt.Println("base64 decode error:", err)
return
}
// 将UTF-8字节切片转为unicode字符串
utf16Runes := utf16.Decode(decodedBytes)
unicodeRunes := utf16.DecodeRune(utf16Runes)
unicodeStr = string(unicodeRunes)
fmt.Println("unicodeStr:", unicodeStr)
fmt.Println("base64Str:", base64Str)
fmt.Println("decodedBytes:", decodedBytes)
}
阅读全文