Skip to content

Instantly share code, notes, and snippets.

@sail1972
Last active January 3, 2024 19:29
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sail1972/c7f2da14d0f284f7d76a5afce7daacfc to your computer and use it in GitHub Desktop.
Save sail1972/c7f2da14d0f284f7d76a5afce7daacfc to your computer and use it in GitHub Desktop.
golang convert UTF16 to UTF8 or UTF8 to UTF16
// from blog of http://angelonotes.blogspot.com/2015/09/golang-utf16-utf8.html
package main
import (
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
"fmt"
)
func main() {
bs_UTF16LE, _, _ := transform.Bytes(unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder(), []byte("測試"))
bs_UTF16BE, _, _ := transform.Bytes(unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM).NewEncoder(), []byte("測試"))
bs_UTF8LE, _, _ := transform.Bytes(unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewDecoder(), bs_UTF16LE)
bs_UTF8BE, _, _ := transform.Bytes(unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM).NewDecoder(), bs_UTF16BE)
fmt.Printf("%v\n%v\n%v\n%v\n", bs_UTF16LE, bs_UTF16BE, bs_UTF8LE, bs_UTF8BE)
}
@Kugelschieber
Copy link

Thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment