复杂二进制分析 - 位翻转和写入二进制文件(Python)

时间:2018-03-16 16:10:30

标签: python python-3.x bit-manipulation binaryfiles

我有一个.bin文件需要读入,位翻转,并写回二进制文件。例如:

RAW INPUT:    \xdd\x00 = 1101110100000000
FINAL OUTPUT: \x00\xbb = 0000000010111011

RAW INPUT:    \x33\x00 = 0011001100000000
FINAL OUTPUT: \x00\xcc = 0000000011001100

我在翻译过程中遇到了困难,其中一些字节将被翻译,而其他字节则不会翻译。在上面的示例中,我可以轻松地翻转二进制位并从\ xdd \ x00获取\ x00 \ xbb,但转换不适用于\ x33 \ 00到\ x00 \ xcc

我目前正在做的是一次读取1个字节,将其转换为整数,获取二进制值,翻转位,然后将其存储到新的二进制文件中。

data = binary_file.read(1)
while data:
    bits = ord(data)                        # Integer Value
    binary = ("{0:b}".format(bits))         # Binary value of Integer
    flipped = 0
    while bits:
        flipped <<=1
        flipped += bits & 1
        bits >>= 1
    data = binary_file.read(1)
    tmp = bytes([flipped])
    output_file.write(tmp)

我完成新文件后,然后将其打开,一次读取两个字节,然后翻转它们:

with open('H:/gitKraken/test.bin', 'rb') as tmp_file:
    print('Flipping Bytes')
    data = tmp_file.read(2)
    final_output = open('final.bin', 'wb')
    while data:
        flip = (data[0], data[1])
        final_output.write(bytes([flip[1]]))
        final_output.write(bytes([flip[0]]))
        data = tmp_file.read(2)

我得到的价值不是我所期待的:

This method works on the following bytes:
Raw Data: \x00\x00\xdd\x00
Expected (Wanted) Value: \x00\x00\x00\xbb
Final Data: \x00\x00\x00\xbb

However, the method does not work on the following bytes:
Raw Data: \x00\x00\x33\x00
Expected (Wanted) Value:: \x00\x00\x00\xcc
Final Data: \x00\x00\x003

关于如何改进此流程并使其真正有效的任何想法?

EDIT1:

以下是我需要如何处理每个字节和最终产品的有效流程:

Hex Bytes (Raw Data)      44           88          22          0
Binary Representation   01000100    10001000    00100010    00000000
Reverse Binary Order    00100010    00010001    01000100    00000000
New Hex Bytes              22          11          44          00
Flip Hex bytes(Final Data) 11          22          00          44

这是另一个使用bytes \ x00 \ x00 \ xdd \ x00

的示例
Hex Bytes (Raw Data)       00          00          dd          00
Binary Representation   00000000    00000000    11011101    00000000
Reverse Binary Order    00000000    00000000    10111011    00000000
New Hex Bytes              00          00          bb          00
Flip Hex bytes(Final Data) 00          00          00          bb

1 个答案:

答案 0 :(得分:1)

你可以这样做:

with open('test.bin', 'rb') as f:
    data = f.read()

def reverse(b):
    return int('{:08b}'.format(b)[::-1], 2)

out = bytearray()   
for i in range(0, len(data), 2):
    out.extend((reverse(data[i+1]), reverse(data[i])))

with open('out.bin', 'wb') as f:
    f.write(out)

相反的部分是nneonneo's answerReversing bits of Python integer