arrays - 戈朗 : calculate diff between two array of bytes and patch an array

标签 arrays go byte diff patch

我试图找到两个字节数组之间的差异并存储增量。

我已阅读此文档 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/

相关文章:

c# - 用于比较的订单日期列表

python - 如何在Go上运行python脚本

c - 如何在 C 中将 int8_t 数组转换为 int32_t 数组

java - Android (Java) 将 JSONArray 转换为 JSONObject

php - 如何计算数组中重复项的出现次数

arrays - 如何迭代两个 byte slice

arrays - 将数组列表复制到 slice 列表工作错误

javascript - js如何将0和1的字符串转换为字节

java - byte[] toString() 给出一个奇怪的字符串而不是实际值

java - 使用二进制搜索在正确的索引处打开数组中的空间