我试图找到两个字节数组之间的差异并存储增量。
我已阅读此文档 https://golang.org/pkg/bytes/
但我没有找到任何说明如何找到差异的内容。
谢谢。
最佳答案
听起来您只需要一个函数,该函数接受两个字节 slice 并返回一个新 slice ,其中包含输入 slice 中每个元素的差异。下面的示例函数断言输入 slice 都是非零的并且具有相同的长度。它还返回一个 int16 slice ,因为字节差异范围是 [-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
}
关于arrays - 戈朗 : calculate diff between two array of bytes and patch an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37640927/