Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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.

like image 695
Ztyx Avatar asked Dec 15 '22 17:12

Ztyx


1 Answers

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.

like image 125
Stephen Weinberg Avatar answered Mar 16 '23 10:03

Stephen Weinberg