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

I have a dimensional byte array that I got after executing md5.Sum() .

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

I get an error message:

cannot convert b (type [16] bytes) to enter a string

+5
source share
4 answers

You can refer to it as a slice:

 pass = string(b[:]) 
+14
source

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

If you are trying to get a hexadecimal representation 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

+10
source

Make it a slice:

 pass = string(b[:]) 
+4
source

he can be solved by this

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

or

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

this will encode it to base64 string

0
source

Source: https://habr.com/ru/post/981258/


All Articles