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

前端 未结 4 2252
后悔当初
后悔当初 2020-12-15 04:48

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 =         


        
相关标签:
4条回答
  • 2020-12-15 04:54

    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

    0 讨论(0)
  • 2020-12-15 04:58

    Make a slice of it:

    pass = string(b[:])
    
    0 讨论(0)
  • 2020-12-15 05:00

    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

    0 讨论(0)
  • 2020-12-15 05:07

    You can refer to it as a slice:

    pass = string(b[:])
    
    0 讨论(0)
提交回复
热议问题