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?
The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).
type uint8 in Golang is the set of all unsigned 8-bit integers. The set ranges from 0 to 255. You should use type uint8 when you strictly want a positive integer in the range 0-255.
Golang bytes Compare() is an inbuilt function that returns an integer comparing two-byte slices lexicographically. The final result will be 0 if a==b, -1 if the a < b, and +1 if a > b. A nil argument is equivalent to the empty slice.
Byte slices are a list of bytes that represent UTF-8 encodings of Unicode code points. Taking the information from above, we could create a byte slice that represents the word “Go”: bs := []byte{71, 111}
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[:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With