【问题标题】:hex header of file, magic numbers, python文件的十六进制标头,幻数,python
【发布时间】:2017-06-14 17:06:23
【问题描述】:

我有一个 Python 程序,它分析文件头并决定它是哪种文件类型。 (https://github.com/LeoGSA/Browser-Cache-Grabber)

问题如下: 我读取了文件的前 24 个字节:

with open (from_folder+"/"+i, "rb") as myfile:
    header=str(myfile.read(24))

然后我在其中寻找模式:

if y[1] in header:
    shutil.move (from_folder+"/"+i,to_folder+y[2]+i+y[3])

在哪里y = ['/video', r'\x47\x40\x00', '/video/', '.ts']

y[1] 是模式并且 = r'\x47\x40\x00'

文件里面有,如下图所示。

程序在文件头中没有找到这个模式(r'\x47\x40\x00')。

所以,我尝试打印标题:

你看到了吗? Python 将其视为 'G@' 而不是 '\x47\x40'

如果我在标题中搜索 'G@'+r'\x00' - 一切正常。它找到了。

问题:我做错了什么?我想寻找r'\x47\x40\x00' 并找到它。不是为了一些奇怪的 'G@'+r'\x00'。

为什么 python 将前两个数字视为 'G@' 而不是 '\x47\x40',而它在 HEX 中看到的其余标题?有办法解决吗?

【问题讨论】:

  • 我会将您从格式化为 HEX 的文件中读出的每一行写入一个临时字符串,然后比较该字符串。
  • 您使用的是哪个 Python 版本?
  • Python 3.4.3 和 3.5
  • 是的,我找到了这样的解决方案:使用 open (from_folder+"/"+i, "rb") as myfile: header=myfile.read(24) header = str(binascii .hexlify(header))[2:-1] 4740001b0000b00d0001c100000001efff3690e23dffffff
  • 如果您不清楚这是怎么发生的,请在交互模式下尝试bytes(range(256)),看看它会给您带来什么。

标签: python file python-3.x header hex


【解决方案1】:
    with open (from_folder+"/"+i, "rb") as myfile:
        header=myfile.read(24)
        header = str(binascii.hexlify(header))[2:-1]

我得到的结果是: 我可以使用它

4740001b0000b00d0001c100000001efff3690e23dffffff

附:但无论如何,如果有人能解释前 2 个字节有什么问题,我将不胜感激。

【讨论】:

    【解决方案2】:

    在 Python 3 中,您将从二进制读取中获取字节,而不是字符串。 无需通过 str 将其转换为字符串。 Print 将尝试将字节转换为人类可读的内容。 如果您不希望这样,请将您的字节转换为例如字节整数值的十六进制表示:

    aBytes = b'\x00\x47\x40\x00\x13\x00\x00\xb0'
    print (aBytes)
    print (''.join ([hex (aByte) for aByte in aBytes]))
    

    从控制台重定向的输出:

    b'\x00G@\x00\x13\x00\x00\xb0'
    0x00x470x400x00x130x00x00xb0
    

    您不能使用in 运算符直接在aBytes 中搜索,因为aBytes 不是字符串而是字节数组。

    如果您想对 '\x00\x47\x40' 应用字符串搜索,请使用:

    aBytes = b'\x00\x47\x40\x00\x13\x00\x00\xb0'
    print (aBytes)
    print (r'\x'.join ([''] + ['%0.2x'%aByte for aByte in aBytes]))
    

    这会给你:

    b'\x00G@\x00\x13\x00\x00\xb0'
    \x00\x47\x40\x00\x13\x00\x00\xb0
    

    所以这里有许多单独的问题:

    • print 尝试打印人类可读的内容,但仅对前两个字符成功。

    • 不能直接在带有in的字节数组中搜索字节数组,所以将其转换为包含固定长度十六进制表示形式的字符串作为子字符串,如图所示。

    【讨论】:

    • b'\x00G@\x00\x13\x00\x00\xb0' Traceback(最近一次调用最后):文件“I:\33.py”,第 3 行,在 打印(''.join ([hex (ord (aByte)) for aByte in aBytes])) 文件“I:\33.py”,第 3 行,在 print (''.join ([hex (ord ( aByte)) for aByte in aBytes])) TypeError: ord() expected string of length 1, but int found [Finished in 0.2s with exit code 1]
    • 对不起,我的错误,使用 Python 2.7,现已更正并测试 3.5。
    猜你喜欢
    • 2013-07-11
    • 2011-06-08
    • 2013-01-18
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2013-03-20
    相关资源
    最近更新 更多