29

I want to compare output of sha256.Sum256() which is [32]byte with a []byte.

I am getting an error "mismatched types [32]byte and []byte". I am not able to convert []byte to [32]byte.

Is there a way to do this?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Sumit Rathore
  • 571
  • 2
  • 7
  • 19

2 Answers2

48

You can trivially convert any array ([size]T) to a slice ([]T) by slicing it:

x := [32]byte{}
slice := x[:] // shorthand for x[0:len(x)]

From there you can compare it to your slice like you would compare any other two slices, e.g.

func Equal(slice1, slice2 []byte) bool {
    if len(slice1) != len(slice2) {
        return false
    }

    for i := range slice1 {
        if slice1[i] != slice2[i] {
            return false
        }
    }

    return true
}

Edit: As Dave mentions in the comments, there's also an Equal method in the bytes package, bytes.Equal(x[:], y[:])

aioobe
  • 413,195
  • 112
  • 811
  • 826
Linear
  • 21,074
  • 4
  • 59
  • 70
-4

I got the answer using this thread

SHA256 in Go and PHP giving different results

    converted := []byte(raw)
    hasher := sha256.New()
    hasher.Write(converted)
    return hex.EncodeToString(hasher.Sum(nil)) == encoded

This is not converting [32]byte to []byte but it is using different function which do not give output in [32]byte.

Community
  • 1
  • 1
Sumit Rathore
  • 571
  • 2
  • 7
  • 19
  • 1
    This might not be applicable to the original question, if `encoded` is a slice of uninterpreted bytes. It only works if `encoded` is to be interpreted as the base64-encoding of the checksum. – dyoo Jan 04 '15 at 07:01