【问题标题】:How to compare [32]byte with []byte in golang?如何在golang中比较[32]byte和[]byte?
【发布时间】:2015-03-01 23:44:34
【问题描述】:

我想将 [32]byte 的 sha256.Sum256() 的输出与 []byte 进行比较。

我收到错误“[32]byte 和 []byte 类型不匹配”。我无法将 []byte 转换为 [32]byte。

有没有办法做到这一点?

【问题讨论】:

    标签: go sha256


    【解决方案1】:

    您可以通过切片轻松地将任何数组 ([size]T) 转换为切片 ([]T):

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

    您可以从那里将其与您的切片进行比较,就像比较任何其他两个切片一样,例如

    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
    }
    

    编辑:正如 Dave 在 cmets 中提到的,bytes 包中还有一个 Equal 方法 bytes.Equal(x[:], y[:])

    【讨论】:

    • 你也可以使用bytes.Equal(x[:], y[:])
    【解决方案2】:

    我通过这个帖子得到了答案

    SHA256 in Go and PHP giving different results

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

    这不是将 [32]byte 转换为 []byte,而是使用了不同的函数,不会在 [32]byte 中给出输出。

    【讨论】:

    • 这可能不适用于原始问题,如果 encoded 是一段未解释的字节。它仅在 encoded 被解释为校验和的 base64 编码时才有效。
    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 2012-03-18
    • 1970-01-01
    • 2020-11-10
    • 2021-06-12
    • 2022-12-01
    • 2013-02-05
    • 2015-06-04
    相关资源
    最近更新 更多