duandui2803 2016-06-05 10:37
浏览 435

Golang:计算两个字节数组之间的差异并修补数组

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.

  • 写回答

1条回答 默认 最新

  • drsl90685154 2017-11-17 20:57
    关注

    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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序