How do I convert [Size]byte to string in Go?

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I have a sized byte array that I got after doing md5.Sum().

data := []byte("testing") var pass string  var b [16]byte b = md5.Sum(data) pass = string(b) 

I get the error:

cannot convert b (type [16]byte) to type string

回答1:

You can refer to it as a slice:

pass = string(b[:]) 


回答2:

A little late but keep in mind that using string(b[:]) will print mostly invalid characters.

If you're trying to get a hex representation of it like php you can use something like:

data := []byte("testing") b := md5.Sum(data)  //this is mostly invalid characters fmt.Println(string(b[:]))  pass := hex.EncodeToString(b[:]) fmt.Println(pass) // or pass = fmt.Sprintf("%x", b) fmt.Println(pass) 

playground



回答3:

Make a slice of it:

pass = string(b[:]) 


回答4:

it can be solved by this

pass = fmt.Sprintf("%x", b) 

or

import "encoding/base64" pass = base64.StdEncoding.EncodeToString(b[:]) 

this will encoding it to base64 string



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!