I'm trying to find the difference between two byte ararys and store the delta.
I've read this documentation https://golang.org/pkg/bytes/
but I didn't find anything that show how to find the diff.
Thanks.
I'm trying to find the difference between two byte ararys and store the delta.
I've read this documentation https://golang.org/pkg/bytes/
but I didn't find anything that show how to find the diff.
Thanks.
Sounds like you just want a function which takes two byte slices and returns a new slice containing the difference of each element in the input slice. The example function below asserts that the input slices are both non-nil and have the same length. It also returns a slice of int16s since the range of difference in bytes is [-255,255]
.
package main
import "fmt"
func main() {
bs1 := []byte{0, 2, 255, 0}
bs2 := []byte{0, 1, 0, 255}
delta, err := byteDiff(bs1, bs2)
if err != nil {
panic(err)
}
fmt.Printf("OK: delta=%v
", delta)
// OK: delta=[0 1 255 -255]
}
func byteDiff(bs1, bs2 []byte) ([]int16, error) {
// Ensure that we have two non-nil slices with the same length.
if (bs1 == nil) || (bs2 == nil) {
return nil, fmt.Errorf("expected a byte slice but got nil")
}
if len(bs1) != len(bs2) {
return nil, fmt.Errorf("mismatched lengths, %d != %d", len(bs1), len(bs2))
}
// Populate and return the difference between the two.
diff := make([]int16, len(bs1))
for i := range bs1 {
diff[i] = int16(bs1[i]) - int16(bs2[i])
}
return diff, nil
}