【问题标题】:What information depicts the quantitative difference between two large given files of the same size?哪些信息描述了两个相同大小的大型给定文件之间的数量差异?
【发布时间】:2011-10-20 09:51:28
【问题描述】:

通常,为了找出两个二进制文件的不同之处,我使用 diff 和 hexdump 工具。但是在某些情况下,如果给定两个相同大小的大型二进制文件,我只想查看它们的数量差异,例如差异区域的数量,累积差异。

示例:2 个文件 A 和 B。它们有 2 个差异区域,它们的累积差异为 6c-a3 + 6c-11 + 6f-6e + 20-22。

File A = 48 65 6c 6c 6f 2c 20 57
File B = 48 65 a3 11 6e 2c 22 57
              |--------|  |--|
                 reg 1   reg 2

如何使用标准 GNU 工具和 Bash 获取此类信息,或者我应该更好地使用简单的 Python 脚本?关于 2 个文件有何不同的其他统计信息也很有用,但我不知道还有什么以及如何衡量?熵差?方差差异?

【问题讨论】:

  • 你在 linux 中已有的 cmp 程序有什么问题? en.wikipedia.org/wiki/Cmp_(Unix)。另外,如果文件大小不同(或比较的区域大小不同),结果如何?
  • 您对“累积差异”的定义意味着00 ffff 00 之间的累积差异为0。这是故意的吗?
  • 作为更一般的说明:如果不指定目的,要求其他“差异措施”是毫无意义的。您可以将这两个文件视为(字节)向量并使用任何有限维向量范数。
  • @sven 1. 这取决于,有时我需要它。但你总是可以只用 abs() 或平方差异 2.目的是对数量差异进行一些统计。

标签: python linux bash statistics hexdump


【解决方案1】:

对于除区域之外的所有内容,您都可以使用numpy。像这样的东西(未经测试):

import numpy as np
a = np.fromfile("file A", dtype="uint8")
b = np.fromfile("file B", dtype="uint8")

# Compute the number of bytes that are different
different_bytes = np.sum(a != b)

# Compute the sum of the differences
difference = np.sum(a - b)

# Compute the sum of the absolute value of the differences
absolute_difference = np.sum(np.abs(a - b))

# In some cases, the number of bits that have changed is a better
# measurement of change. To compute it we make a lookup array where 
# bitcount_lookup[byte] == number_of_1_bits_in_byte (so
# bitcount_lookup[0:16] == [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4])
bitcount_lookup = np.array(
    [bin(i).count("1") for i in range(256)], dtype="uint8")

# Numpy allows using an array as an index. ^ computes the XOR of
# each pair of bytes. The result is a byte with a 1 bit where the
# bits of the input differed, and a 0 bit otherwise.
bit_diff_count = np.sum(bitcount_lookup[a ^ b])

我找不到用于计算区域的 numpy 函数,但只需使用 a != b 作为输入编写您自己的函数,应该不难。请参阅this 问题以获取灵感。

【讨论】:

  • 谢谢,它看起来是一个有趣的解决方案。
【解决方案2】:

想到的一种方法是对二进制差异算法进行一些修改。例如。 a python implementation of the rsync algorithm。从那开始应该相对容易地为您提供文件不同的块范围列表,然后对这些块进行任何您想要做的统计。

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 2021-06-10
    • 2012-01-20
    • 2015-11-21
    • 2014-10-24
    • 2021-01-01
    相关资源
    最近更新 更多