doupafu6980 2019-06-04 04:14
浏览 55
已采纳

我可以破坏[] byte和字符串之间的数据转换吗?

In Go, if I convert from a string -> []byte or conversely, from []byte -> string, could the data ever get corrupted. For example, let's say I've defined:

fooBytes := []byte(fooString)
fooConvertedBack := string(fooBytes
fooBytesConvertedBack := []byte(fooConvertedBack)

Then could we get a case where data gets corrupted such that:

fooString != fooConvertedBack
fooBytes != fooBytesConvertedBack

I'm guessing the answer here is no. I'm working with random arrays of bytes and I want to make sure that I won't corrupt data because, say for example, a golang string has a default character set which doesn't allow for completely random bytes.

Is it better to base64 encode the bytes?

  • 写回答

3条回答 默认 最新

  • doubeijian2257 2019-06-04 07:59
    关注

    As Cerise Limón wrote, it won't be corrupted. Converting between string and []byte does not interpret the bytes, it just copies them as-are.

    Do note however that if you would convert between string and []rune, that might change the content becase as written in Spec: Conversions to and from a string type:

    Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string.

    So this conversion decodes the runes (Unicode codepoints), and if the input string is not a valid UTF-8 encoded text, the Unicode replacement character 0xFFFD will be used in such cases.

    For example a string containing a single 0xff byte is not a valid UTF-8 encoded text:

    fooString := "\xff"
    barString := string([]rune(fooString))
    fmt.Println(fooString == barString)
    fmt.Printf("%x %x", fooString, barString)
    

    Outputs (try it on the Go Playground):

    false
    ff efbfbd
    

    (Note: the hex efbfdb is the 3-byte UTF-8 encoded value of the Unicode replacement character 0xFFFD.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看