code that will take a binary file and searching for a byte pattern and then print to a new text file. code written in python. printing the data from the binary to human legible text. prints data when pattern in found.
The code for the above problem:
#Function for pattern search =============================
def search(pat, txt):
flag = 0
M = len(pat)
N = len(txt)
for i in range(N - M + 1):
j = 0
while(j < M):
if (txt[i + j] != pat[j]):
break
j += 1
if (j == M):
print("Pattern found at index ", i)
flag = 1
return flag
#Create binary file ===================================
with open('Bin_file.bin', 'wb') as f:
bin_input = input("Enter the string : ")
bin_input = ' '.join(format(x, 'b') for x in bytearray(bin_input, 'utf-8'))
bin_input = bytes(bin_input, 'utf-8')
A = f.write(bin_input)
#Open binary file ======================================
with open('Bin_file.bin', 'rb') as f:
s = f.read()
#convert byte formate to string
txt = s.decode('utf-8')
print(txt)
#Take input of the searched pattern
pat = input("Enter the pattern you want to search : ")
Sear = search(pat, txt)
binary_values = pat.split()
ascii_string = ""
#Convert from binary to character
for binary_value in binary_values:
an_integer = int(binary_value, 2)
ascii_character = chr(an_integer)
ascii_string += ascii_character
#Create new text file and write to convert the pattern to human language
if(Sear == 1):
with open('new_text.txt', 'w') as f:
h_lang = ascii_string
B = f.write(h_lang)
with open('new_text.txt', 'r') as f:
B = f.read()
print(B)
Output:
Get Answers For Free
Most questions answered within 1 hours.