duanhangjian8149 2019-01-30 12:47
浏览 331

Go中等效的C#的Encoding.UTF8.GetString [关闭]

Whats the equivalent of C#'s Encoding.UTF8.GetString in Go?

As i already know that Go's default encoding is in UTF8 and string(somebytes) in Go would produce a UTF8 encoded string.

C#:

public static void Main()
{
    byte[] bytes = new byte[] { 144, 197, 217, 192, 204, 249, 181, 42, 92, 252, 243, 87, 170, 243, 169, 80, 175, 112, 192, 239};
    string str = Encoding.UTF8.GetString(bytes);

    Console.WriteLine(str);
 }

Go:

func main() {
bytes := []byte { 144, 197, 217, 192, 204, 249, 181, 42, 92, 252, 243, 87, 170, 243, 169, 80, 175, 112, 192, 239}
str := string(bytes)
fmt.Println(str)
}

C# code produces:

�������*\��W��P�p��

Go code produces:

�������*\��W���P�p��

what I am missing here?

  • 写回答

1条回答 默认 最新

  • douhuike3199 2019-01-30 13:11
    关注

    Clearly, whatever way you look at it, your bytes are not valid UTF-8.

    For example,

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        bytes := []byte{144, 197, 217, 192, 204, 249, 181, 42, 92, 252, 243, 87, 170, 243, 169, 80, 175, 112, 192, 239}
        fmt.Println(len(bytes))
        fmt.Printf("%v
    ", bytes)
        fmt.Printf("% x
    ", bytes)
        fmt.Printf("%q
    ", bytes)
        fmt.Printf("%s
    ", bytes)
    }
    

    Playground: https://play.golang.org/p/bHhkeGuZcCK

    Output:

    20
    [144 197 217 192 204 249 181 42 92 252 243 87 170 243 169 80 175 112 192 239]
    90 c5 d9 c0 cc f9 b5 2a 5c fc f3 57 aa f3 a9 50 af 70 c0 ef
    "\x90\xc5\xd9\xc0\xcc\xf9\xb5*\\\xfc\xf3W\xaa\xf3\xa9P\xafp\xc0\xef"
    �������*\��W���P�p��
    

    References:

    The Unicode Consortium

    Unicode: UTF-8, UTF-16, UTF-32 & BOM

    UTF-8 - Wikipedia

    The Go Blog: Strings, bytes, runes and characters in Go

    Go: Package utf8

    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用