search for a binary string in binary file with python

2.9k views Asked by At

Hi all am searching for a binary string in binary file using the python

my binary file looks like a as follows.

I want to find the bold text below.

00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 21 00 37 28 23 00 3C 2D 58 F3 91 E2 00 00 01 00 97 00 01 00 FF 01 48 00 C1 3B 51 8C DA A8 B0 EE 05 F8 F5 41 17 BA B1 DD 22 88 06 5E BE D4 D3 F3 EF 96 19 3A 26 D1 B3 25 50 7B 38 DD DA 96 0A 9F D0 9B A4 30 68 F5 2E 63 58 13 78 C7 F3 8A 59 FD 35 08 F9 13 5B 63 63 14 C8 12 6D 2E F1 B9 DA 7E 97 8F 1B 5E 19 67 DF A6 AA 5F 79 64 C5 04 FD 2E F8 7F 35 7D

Here is my code, my code is able to find the individual bytes as "58", "F3", "92", etc.. but not finding/ searching as a whole string.

        with open(binary_file, 'r+b') as f:
        s = f.read()
        d = bytes(hex_string, 'utf-8')
        n = s.find(d)
        if n > -1:
            print(n)
        else:
            print("string not found")
           

can you guys, help me out finding the whole string. Thanks in advance.

1

There are 1 answers

0
ForceBru On BEST ANSWER

bytes(hex_string, 'utf-8') will convert your hex string to bytes character-by-character. For example:

bytes('BEEF', 'utf-8') == b'BEEF'

So you'll end up searching for four bytes in b'BEEF': [66, 69, 69, 70]. You're looking for the fromhex method:

>>> bytes.fromhex('BEEF')
b'\xbe\xef'