local-host 2013-01-09 07:19 采纳率: 100%
浏览 687
已采纳

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

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

  • 写回答

10条回答 默认 最新

  • ℙℕℤℝ 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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python