如何将 []byte 转换为 [16]byte?

huangapple go评论71阅读模式
英文:

How can I convert from []byte to [16]byte?

问题

我有这段代码:

func my_function(hash string) [16]byte {
    b, _ := hex.DecodeString(hash)
    return b   // 编译错误:因为 [16]byte != []byte,所以失败了
}

b 的类型将是 []byte。我知道 hash 的长度为 32。如何使上面的代码工作?也就是说,我是否可以将一个通用长度的字节数组转换为固定长度的字节数组?我不想分配 16 个新字节并复制数据。

英文:

I have this code:

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

b will be of type []byte. I know that hash is of length 32. How can I make my code above work? Ie. can I somehow cast from a general-length byte array to a fixed-length byte array? I am not interested in allocating 16 new bytes and copying the data over.

答案1

得分: 12

没有直接将切片转换为数组的方法。但是你可以进行复制操作。

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

标准库使用[]byte,如果你坚持使用其他类型,那么你需要更多的输入。我曾经使用数组来编写我的MD5值的程序,但后悔了。

英文:

There is no direct method to convert a slice to an array. You can however do a copy.

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

The standard library uses []byte and if you insist on using something else you will just have a lot more typing to do. I wrote a program using arrays for my md5 values and regretted it.

huangapple
  • 本文由 发表于 2015年1月3日 03:35:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/27747571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定