Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare [32]byte with []byte in golang?

Tags:

go

sha256

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?

like image 313
Sumit Rathore Avatar asked Jan 04 '15 05:01

Sumit Rathore


People also ask

What is a [] byte in Golang?

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 ).

What is [] uint8 in Golang?

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.

How do you compare bytes in Go?

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.

What is byte 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}


1 Answers

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[:])

like image 195
Linear Avatar answered Sep 22 '22 15:09

Linear