gpt4 book ai didi

go - 如何从 []byte 转换为 [16]byte?

转载 作者:IT王子 更新时间:2023-10-29 01:22:14 26 4
gpt4 key购买 nike

我有这个代码:

func my_function(hash string) [16]byte {
b, _ := hex.DecodeString(hash)
return b // Compile error: fails since [16]byte != []byte
}

b 将是 []byte 类型。我知道 hash 的长度为 32。如何使上面的代码工作? IE。我可以以某种方式从通用长度字节数组转换为固定长度字节数组吗?我对分配 16 个新字节并复制数据不感兴趣。

最佳答案

没有直接的方法可以将 slice 转换为数组。但是,您可以复制一份。

var ret [16]byte
copy(ret[:], b)

标准库使用 []byte,如果你坚持使用其他东西,你将需要做更多的输入工作。我为我的 md5 值编写了一个使用数组的程序并后悔了。

关于go - 如何从 []byte 转换为 [16]byte?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27747571/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com