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 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug