英文:
How to compare [32]byte with []byte?
问题
我想要比较sha256.Sum256()
的输出结果,它是一个[32]byte
类型,与一个[]byte
类型进行比较。
我遇到了一个错误,错误信息是“类型不匹配,[32]byte和[]byte”。我无法将[]byte
转换为[32]byte
。
有没有办法可以做到这一点?
英文:
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?
答案1
得分: 47
你可以通过切片操作将任何数组([size]T)轻松转换为切片([]T):
x := [32]byte{}
slice := x[:] // 简写形式,等同于 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在评论中提到的,bytes
包中还有一个Equal
方法,可以使用bytes.Equal(x[:], y[:])
进行比较。
英文:
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[:])
答案2
得分: -4
我使用这个线程找到了答案:
https://stackoverflow.com/questions/16111754/sha256-in-go-and-php-giving-different-results?rq=1
converted := []byte(raw)
hasher := sha256.New()
hasher.Write(converted)
return hex.EncodeToString(hasher.Sum(nil)) == encoded
这段代码并没有将[32]byte转换为[]byte,而是使用了一个不会输出[32]byte的不同函数。
英文:
I got the answer using this thread
https://stackoverflow.com/questions/16111754/sha256-in-go-and-php-giving-different-results?rq=1
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论