dongyao2022 2013-01-09 07:19
浏览 116
已采纳

如何将零终止的字节数组转换为字符串?

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.

  • 写回答

12条回答 默认 最新

  • dongzhouhao4316 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 微信小程序协议怎么写
  • ¥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 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看