douken7402
douken7402
2015-01-02 19:35

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

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条回答

  • douxian7534 douxian7534 6年前

    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.

    点赞 评论 复制链接分享

为你推荐