golang实现base转换为utf-8
时间: 2023-05-27 20:02:55 浏览: 139
Golang GBK转UTF-8的例子
package main
import (
"fmt"
"strings"
)
var base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
func baseToBinary(b byte) string {
idx := strings.IndexByte(base, b)
if idx == -1 {
return ""
}
return fmt.Sprintf("%06b", idx)
}
func binaryToUTF8(b string) string {
utf8 := ""
for len(b) > 0 {
r, size := utf8Decode(b)
utf8 += string(r)
b = b[size:]
}
return utf8
}
func utf8Decode(b string) (r rune, size int) {
if len(b) == 0 {
return 0, 0
}
firstByte := b[0]
if firstByte < 0x80 {
return rune(firstByte), 1
}
masks := []byte{0x7f, 0x3f, 0x1f, 0x0f}
mask := masks[(firstByte>>3)&0x03]
r = rune(firstByte & mask)
size = 2
if firstByte&0xe0 == 0xc0 {
mask = masks[0]
r |= rune((b[1] & mask) << 6)
} else if firstByte&0xf0 == 0xe0 {
mask = masks[1]
r |= rune((b[1] & mask) << 6)
r |= rune(b[2] & 0x3f)
size = 3
} else if firstByte&0xf8 == 0xf0 {
mask = masks[2]
r |= rune((b[1] & mask) << 6)
r |= rune((b[2] & 0x3f) << 6)
r |= rune(b[3] & 0x3f)
size = 4
}
return r, size
}
func baseToUTF8(s string) (string, error) {
if len(s)%4 != 0 {
return "", fmt.Errorf("invalid base string")
}
var binary string
for i := 0; i < len(s); i += 4 {
block := s[i : i+4]
binary += baseToBinary(block[0])
binary += baseToBinary(block[1])
binary += baseToBinary(block[2])
binary += baseToBinary(block[3])
}
return binaryToUTF8(binary), nil
}
func main() {
baseString := "SGVsbG8gV29ybGQh"
utf8String, err := baseToUTF8(baseString)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(utf8String) // Output: "Hello World!"
}
阅读全文