1

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.

Alex. b
  • 669
  • 2
  • 10
  • 18
  • Do you just need to know if `bytesA[i] != bytesB[i]`? Or are you actually trying to see a delta in the value of the two bytes? – Snowman Jun 05 '16 at 12:47
  • @Snowman I need to find the delta. – Alex. b Jun 05 '16 at 17:06
  • OK. that could be trivial, or it actually could be really complex. See if this works for your use case: https://play.golang.org/p/NagbPPlSjn. There are some things that it would *have* to take care of in actual production code which are omitted from the example, but it demonstrates the gist of what I think you're trying to make happen. – Snowman Jun 05 '16 at 18:04

1 Answers1

1

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\n", 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
}
maerics
  • 151,642
  • 46
  • 269
  • 291