旧行李 2013-01-09 07:19 采纳率: 25%
浏览 295
已采纳

将字节数组转换为字符串的最佳方法是什么?

I need to read [100]byte to transfer a bunch of string data.

Because not all of the strings are precisely 100 characters long, the remaining part of the byte array are padded with 0s.

If I tansfer [100]byte to string by: string(byteArray[:]), the tailing 0s are displayed as ^@^@s.

In C the string will terminate upon 0, so I wonder what's the best way of smartly transfer a byte array to string in Golang.

转载于:https://stackoverflow.com/questions/14230145/what-is-the-best-way-to-convert-byte-array-to-string

  • 写回答

12条回答 默认 最新

  • 七度&光 2013-01-09 07:24
    关注

    methods that read data into byte slices return the number of bytes read. You should save that number and then use it to create your string. n being the number of bytes read, your code would look like this:

    s := string(byteArray[:n])
    

    If for some reason you don't have n, you could use the bytes package to find it, assuming your input doesn't have a null character in it.

    n := bytes.Index(byteArray, []byte{0})
    

    Or as icza pointed out, you can use the code below:

    n := bytes.IndexByte(byteArray, 0)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料